【问题标题】:Assigned legend colors don't work/show分配的图例颜色不起作用/显示
【发布时间】:2018-07-07 05:42:00
【问题描述】:

我对 R 很陌生。 我正在尝试创建一个密度图,这不是问题,这要归功于这里以前的问题和答案。

我目前的问题是图表的图例。我已经分配了想要的颜色 (col = c("red", "orange", "yellow", "green", "blue", "purple")),但它们并没有显示在图例本身上,而是我得到了随机颜色。 我认为重要的是要提到运行代码后没有错误并且我检查了所有这些颜色是否可用here

这是密度图代码,以及图例信息。

plot(density(df$a1), col = "red", xlim = c(0, 1000), ylim = c(0, 0.004))
lines(density(df$a2), col = "orange")
lines(density(df$a3), col = "yellow")
lines(density(df$a4), col = "green")
lines(density(df$a5), col = "blue")
lines(density(df$a6), col = "purple")
legend(x = "topright", legend = names(df), fill = 1:6, col = c("red", "orange", "yellow", "green", "blue", "purple"))

然而,结果是这样的:

谢谢!

【问题讨论】:

    标签: r plot colors legend kernel-density


    【解决方案1】:

    fill 指定框的颜色,而col 指定点和线的颜色。

    在你的情况下,代码应该是:

    legend(x = "topright", legend = names(df), lty=1, col = c("red", "orange", "yellow", "green", "blue", "purple"))
    

    lty=1 表示您希望用实线代替方框(lty 代表 line type)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-08
      • 1970-01-01
      • 1970-01-01
      • 2017-03-17
      • 2021-10-29
      • 1970-01-01
      • 2021-11-12
      相关资源
      最近更新 更多