'How to create a stand alone legend in R
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:
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
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.
Solution 1:[1]
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')
ltype <- c(1, 1, 1, 2, 1, 1)
plot(NULL ,xaxt='n',yaxt='n',bty='n',ylab='',xlab='', xlim=0:1, ylim=0:1)
legend("topleft", title="Continent", legend = names, lty=ltype, lwd=2, cex=1.25,
bty='n', col = clrs)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |