首页 > 解决方案 > 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:

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.

标签: rggplot2plotlegend

解决方案


我认为这更接近你想要的。如果您想要线条,请不要绘制符号。阅读 legend() 的手册页。这很令人困惑,但有很多选择。基本图形与 ggplot 不同,它们不容易网格化。

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)

传奇


推荐阅读