R:根据因子水平的图例颜色

问题描述 投票:1回答:1

this问题的启发,显然最佳答案是使用不安全/错误的方式为散点图的图例添加颜色。

最佳答案建议这样做:

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()调用中的文本和颜色,但不清楚为什么它会有所帮助。我需要一个更好的解释来信任该代码。

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

r legend r-factor
1个回答
0
投票

我发现的解决方案是:

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变量,该变量用作因子级别(在这种情况下为虹膜种类)和图例颜色之间的转换表。

© www.soinside.com 2019 - 2024. All rights reserved.