【问题标题】:R:ensuring legend colors match the defined colorsR:确保图例颜色与定义的颜色匹配
【发布时间】:2021-04-27 11:10:22
【问题描述】:

我正在使用 R 编程语言。使用著名的 Iris 数据集,我创建了以下图:

require(MASS)
cols = c('red', 'green', 'blue')
parcoord(iris[ ,-5], col = cols[iris$Species])

从这里,我尝试添加一个图例:

legend("topright", c("setosa", "versicolor", "virginica"), lwd = 2, col = iris$Species, bty = "n")

如何确保图例颜色与图表上的颜色真正匹配? R 会自动执行此操作吗?

谢谢

【问题讨论】:

  • 在图例中也使用颜色矢量的索引:col = cols[unique(iris$Species)]
  • @user12728748,请发表您的评论作为答案...?

标签: r plot data-visualization legend


【解决方案1】:

iris$Species 是一个具有 3 个(整数)级别和相关名称的因子:

require(MASS)
str(iris$Species)
#>  Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

因此,使用cols[iris$Species] 根据因子级别分配颜色,setosa 是第一个(红色),等等。

您可以重新调整因素,这将影响颜色与物种的关联并改变颜色(setosa 为 2,因此为绿色),以展示这种效果:

iris$Species <- relevel(iris$Species, "versicolor")
str(iris$Species)
#>  Factor w/ 3 levels "versicolor","setosa",..: 2 2 2 2 2 2 2 2 2 2 ...

图例仅显示 3 个名称和颜色,因此您可以使用因子级别和相关名称来确保它们匹配。由于我们在这里更改了顺序,所以我们得到了这样的结果:

require(MASS)
cols = c('red', 'green', 'blue')
iris$Species <- relevel(iris$Species, "versicolor")
parcoord(iris[ ,-5], col = cols[iris$Species])
legend("top", levels(iris$Species), lwd = 2, col = cols, bty = "n")

reprex package (v0.3.0) 于 2021-01-22 创建

【讨论】:

    【解决方案2】:

    这里,irisSpecies 列是一个因素(尝试运行 class(iris$Species))。如果你然后运行levels(iris$Species),你会看到级别的顺序是setosa versicolor virginica

    如果您将此因子转换为整数值(尝试as.integer(iris$Species)),您将看到setosa = 1、versicolor = 2 和virginica = 3。当您将cols[iris$Species] 作为parcoord() 的参数,你使用这个因子作为索引,R 默默地将它转换为整数向量。因此setosa会映射到cols的第一个元素,即'red',以此类推。

    请看下面:

    require(MASS)
    cols = c('red', 'green', 'blue')
    parcoord(iris[ ,-5], col = cols[iris$Species])
    legend("topright", levels(iris$Species), lwd = 2, col = cols, inset = 0.05)
    

    这将产生以下情节:

    虽然基本 R 图形可能足以满足您的用例,但我强烈建议您探索 ggplot2 包以获得更高级和可自定义的图形。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多