R:根据要素级别的图例颜色 [英] R: Legend color according to factor levels

查看:85
本文介绍了R:根据要素级别的图例颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的启发 问题是最明显的答案是在哪里使用不安全/错误的方式为散点图添加颜色到图例.

Inspired by this question where apparently the top answer is using an unsafe/erroneous way to add colors to a legend for a scatter plot.

最佳答案建议这样做:

data<-iris
plot(data$Sepal.Length, data$Sepal.Width, col=data$Species)
legend(7,4.3,unique(data$Species),col=1:length(data$Species),pch=1)

评论建议使用levels()而不是unique()来控制对legend()的调用中的文本和颜色,但是尚不清楚为什么会有所帮助.我需要一个更好的解释来信任该代码.

Comments suggest using levels() instead of unique() for controlling the text and colors in the call to legend(), but are unclear on why it would help. I would need a better explanation to trust that code.

如何编写保证正确着色的代码?

How can I write code that guarantees proper coloring?

推荐答案

我找到的解决方案是:

data <- iris
# Create a translation table that couple species to color
colorcode = data.frame(
  cbind(colorsMy = c("red", "green", "blue"), species = levels(data$Species)),
  stringsAsFactors = F)
# Make vector with colors for the different points in the scatter
iriscolors = sapply(data$Species,  # Species to colors translation acc to colorcode
                    function(x) colorcode$colorsMy[colorcode$species == x])
# Plot the scatter using the color vector constructed according the colorcode
plot(data$Sepal.Length, data$Sepal.Width, col = iriscolors, pch = 19)
# Since iriscolors according to colorcode, I can use colorcode for the legend
legend("bottomright", legend = colorcode$species, fill = colorcode$colorsMy)

此代码有点笨重,但易于遵循,并在图例中显式构造了正确的颜色标签. 技巧"是创建colorcode变量,该变量用作因子级别(在这种情况下为虹膜种类)和图例颜色之间的转换表.

This code is a bit bulky, but easy to follow and explicitly constructs correct color labeling in the legend. The "trick" is to create the colorcode variable that serves as a translation table between levels of the factor (iris species in this case) and colors for the legend.

这篇关于R:根据要素级别的图例颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆