2
votes

This is a slightly different but very similar question to How can i create a legend without a plot in r but differs in that I do not want to use the -pch- option in -plot( )- but rather I would like to create legend that represents different time series plots overlaid. What I am trying to create is:

enter image description here

The above legend is created using -ggplot( )- but I am creating 6 plots that have identical legends and want to suppress the legends and create a stand-alone legend that represents all. I cannot just create an array of plots in R, the coordinator of the project I am working on insists I create separate plots and try to make a separate legend so this is my work around.

Currently I have adapted the linked question from above and created this:

legend <- plot(NULL ,xaxt='n',yaxt='n',bty='n',ylab='',xlab='', xlim=0:1, ylim=0:1)
legend("topleft", legend =c('Africa', 'Asia', 'Europe', 'North America', 'Oceania', "South America"), pch=16, pt.cex=7, cex=1.5, bty='n',
    col = c('orange', 'red', 'green', 'blue', 'purple'))
mtext("Continent", at=0.2, cex=2)
legend

enter image description here

And the colours do not match up, although I am sure I can update them on my own after getting some help on the main issue.

I suppose my overall question is how am I supposed to do this? I looked through all of the values for the option -pch=" "- but they are all just symbols so I am unsure where to go from here.

1
Have you seen the cowplot article on shared legends for ggplot2 plots? That seems like it'd really help you do what you want to do. - aosmith
That is a very useful article thank you for sharing it! I would regularly do something similar; however, I ideally need to create a separate image for the legend as we are manually placing it in a word document next to the images of the plots for a research paper. If this isn't possible (I think it must be) then I will definitely use the -cowplot- function and just create an array of the plots! - Brennan
You can capture the legend as shown in the article and then plot only the legend with plot_grid() or ggdraw() so you can save it with ggsave() (with appropriate height/width for such a small plot). - aosmith

1 Answers

4
votes

I think this is closer to what you want. Don't plot symbols if you want lines. Read the manual page for legend(). It is confusing, but there are many options. Basic graphics is different from ggplot and they do not mesh easily.

names <- c('Africa', 'Asia', 'Europe', 'North America', 'Oceania',
         'South America')
clrs <- c('orange', 'red', 'green', 'blue', 'purple')
plot(NULL ,xaxt='n',yaxt='n',bty='n',ylab='',xlab='', xlim=0:1, ylim=0:1)
legend("topleft", title="Continent", legend = names, lty=1, lwd=2, cex=1.25,
     bty='n', col = clrs)

Legend