简体   繁体   English

R图中图例/颜色不匹配

[英]Mismatch in legend/color in R plot

I created several plots in R. Occasionally, the program does not match the color of the variables in the plot to the variable colors in the legend. 我在R中创建了多个绘图。有时,程序与绘图中的变量颜色与图例中的变量颜色不匹配。 In the attached file (Unfortunately, I can't yet attach images b/c of reputation), the first 2 graphs are assigned a black/red color scheme. 在附件文件中(不幸的是,我尚无法附加声誉的图像b / c),前2个图分配了黑色/红色配色方案。 But, the third chart automatically uses a green/black and keeps the legend with black/red. 但是,第三个图表会自动使用绿色/黑色,并将图例保留为黑色/红色。 I cannot understand why this happens. 我不明白为什么会这样。

How can I prevent this from happening? 如何防止这种情况发生? I know it's possible to assign color, but I am struggling to find a clear way to do this. 我知道可以分配颜色,但是我一直在努力寻找一种清晰的方法来进行分配。

Code: 码:

plot(rank, abundance, pch=16, col=type, cex=0.8)
legend(60,50,unique(type),col=1:length(type),pch=16)

plot(rank, abundance, pch=16, col=Origin, cex=0.8)
legend(60,50,unique(Origin),col=1:length(Origin),pch=16)


Below is where color pattern won't match

plot(rank, abundance, pch=16, col=Lifecycle, cex=0.8)
legend(60,50,unique(Lifecycle),col=1:length(Lifecycle),pch=16)

data frame looks like this: 数据框如下所示:

Plant    rank   abundance  Lifecycle    Origin   type
X         1         23       Perennial   Native  Weedy
Y         2         10       Annual      Exotic  Ornamental
Z         3         9        Perennial   Native  Ornamental

First, I create some fake data. 首先,我创建一些虚假数据。

 df <- data.frame(rank = 1:10, abundance = runif(10,10,100), 
       Lifecycle = sample(c('Perennial', 'Annual'), 10, replace=TRUE))

Then I explicitly say what colors I want my points to be. 然后,我明确地说出我想要的点是什么颜色。

cols=c('dodgerblue', 'plum')

Then I plot, using the factor df$Lifecycle to color points. 然后,我使用因子df$Lifecycle绘制颜色点。

plot(df$rank, df$abundance, col = cols[df$Lifecycle], pch=16)

When the factor df$Lifecycle is used above, it converts it to a numeric reference to cols , such that it sorts the values alphabetically. 在上面使用因子df$Lifecycle ,它将其转换为对cols的数字引用,以便按字母顺序对值进行排序。 Therefore, in the legend, we just need to sort the unique df$Lifecycle values, and then hand it our color vector ( cols ). 因此,在图例中,我们只需要对唯一的df$Lifecycle值进行排序,然后将其传递给我们的颜色矢量( cols )。

legend(5, 40, sort(unique(df$Lifecycle)), col=cols, pch=16, bty='n')

Hopefully this helps. 希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM