【问题标题】:Colors mysteriously shuffled in the plot颜色在情节中神秘地洗牌
【发布时间】:2020-06-25 15:35:25
【问题描述】:

在 R 中使用以下 ggplot2 代码:

require(ggplot2)
df <- data.frame(x = rep(c(0, 1, 1.58,2, 2.58, 3, 3.32, 3.58, 4.17, 4.58, 5.58, 6.17, 6.5, 7.0),4), y = c(0.15,0.17,0.07,0.17,0.01,0.15,0.18,0.04,-0.06,-0.08,0,0.03,-0.27,-0.93,0.04,0.12,0.08,0.15,0.04,0.15,0.03,0.09,0.11,0.13,-0.11,-0.32,-0.7,-0.78,0.07,0.04,0.06,0.12,-0.15,0.05,-0.08,0.14,-0.02,-0.14,-0.24,-0.32,-0.78,-0.81,-0.04,-0.25,-0.09,0.02,-0.13,-0.2,-0.04,0,0.02,-0.05,-0.19,-0.37,-0.57,-0.81))
ggplot(df, aes(x = x, y = y)) + geom_point() + 
   stat_smooth(method = "lm", formula = y ~ x, size = 1, se = FALSE, aes(color = "black")) + 
   stat_smooth(method = "lm", formula = y ~ poly(x, 2), size = 1, se = FALSE, aes(color = "green")) + 
   stat_smooth(method = "lm", formula = y ~ poly(x, 3), size = 1, se = FALSE, aes(color = "orange")) + 
   stat_smooth(method = "gam", formula = y ~ s(x), size = 1, se = FALSE, aes(color = "blue")) +
   theme(legend.justification=c(1,1),legend.position=c(0.45,0.45),legend.title=element_blank()) +
   scale_color_manual(values=c("black","green","orange","blue"), labels=c("linear","quadratic","cubic","smooth")) 

传说很好;但由于某种原因,四条曲线中的三条没有按预期着色:橙色曲线应为绿色,蓝色曲线应为橙色,绿色曲线应为蓝色。我错过了什么?

【问题讨论】:

  • 为颜色传递一个命名向量以获得正确的顺序(如values = c("black" = "black", ...) 或尝试scale_color_identity() 和guide = "legend" (因为身份比例默认为无指导)。我有一个例子这在一篇博文中here。

标签: r ggplot2 colors


【解决方案1】:

你在审美调用中使用的字符串是任意的(即使你在颜色之后调用它们)。它们将在 ggplot 内部转换为因子列,并且因子的水平按字母顺序确定。因子水平被映射到scale_color_manual 调用中的值向量按照它们的放置顺序。

因此,您可以将“a”到“d”用作任意字符串,以实现颜色美学来跟踪它们并控制它们的顺序:

ggplot(df, aes(x = x, y = y)) + 
  geom_point() + 
   stat_smooth(method = "lm", formula = y ~ x, 
               size = 1, se = FALSE, aes(color = "a")) + 
   stat_smooth(method = "lm", formula = y ~ poly(x, 2), 
               size = 1, se = FALSE, aes(color = "b")) + 
   stat_smooth(method = "lm", formula = y ~ poly(x, 3), 
               size = 1, se = FALSE, aes(color = "c")) + 
   stat_smooth(method = "gam", formula = y ~ s(x), 
               size = 1, se = FALSE, aes(color = "d")) +
   theme(legend.justification = c(1, 1),
         legend.position      = c(0.45, 0.45),
         legend.title         = element_blank()) +
   scale_color_manual(values = c("black", "green", "orange", "blue"),
                      labels = c("linear", "quadratic", "cubic", "smooth")) 

【讨论】:

    【解决方案2】:

    来自在线帮助(我的重点):

    价值观
    一组美学值来映射数据值。这些值将按顺序(通常按字母顺序)与比例的限制相匹配,或者如果提供了中断。如果这是一个命名向量,则将根据名称匹配值。不匹配的数据值将被赋予 na.value。

    所以试试

    values=c("linear"="black","quadratic"="green","cubic"="orange","smooth"="blue")
    

    或类似的东西。我无法检查我的代码,因为您没有提供输入数据。

    【讨论】:

      猜你喜欢
      • 2019-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-07
      • 2020-02-23
      • 1970-01-01
      相关资源
      最近更新 更多