【问题标题】:Change colour of jitter points according to facet_wrap根据 facet_wrap 改变抖动点的颜色
【发布时间】:2019-05-30 15:46:15
【问题描述】:

我想比较两个不同地点的不同颜色花朵(红色和绿色)的数量。我在 ggplot2 中有一个箱线图,背景中有一个抖动图。我希望抖动点的颜色根据花朵的颜色而有所不同。不知道该怎么做!有没有办法根据花的颜色对我的刻面进行颜色编码?

一些样本数据:

site <- c(rep(1, 4), rep(2, 4))

colour <- c("red", "green", "red", "green", "red", "green", "red", "green")
number <- c(12, 24, 22, 14, 12, 16, 18, 17)

df <- data.frame(site, colour, number)
df$site <- as.factor(df$site)

ggplot(df, aes(site, number))+
  facet_wrap("colour")+
  geom_jitter(alpha = 0.3) +
  geom_boxplot(alpha = 0, colour = "black")+
  theme(legend.position = "none")

【问题讨论】:

    标签: r ggplot2 facet-wrap


    【解决方案1】:
    ggplot(df, aes(site, number))+
      facet_wrap(~colour)+
      geom_jitter(aes(col = colour), alpha = 0.3, show.legend = F) +
      geom_boxplot(alpha = 0, colour = "black")+
      scale_color_manual(values = c("green", "red"))
    

    【讨论】:

      【解决方案2】:

      将颜色映射到您的列名。如果您希望从字面上解释颜色,请使用身份标度:

      ggplot(df, aes(site, number))+
        facet_wrap(colour)+
        geom_jitter(aes(colour = colour), alpha = 0.3) +
        geom_boxplot(alpha = 0, colour = "black") +
        scale_color_identity() +
        theme(legend.position = "none")
      

      【讨论】:

        【解决方案3】:

        虽然这里的两个答案都解决了您的问题,但我认为它们不必要地令人费解。

        ggplot(df, aes(site, number)) +
          facet_wrap(~colour) +
          geom_jitter(alpha = 0.3, color = colour) +
          geom_boxplot(alpha = 0, color = "black")
        

        reprex package (v0.3.0) 于 2019 年 5 月 30 日创建

        • 您不需要theme(legend.position = "none"),因为在您的geoms 中您在aes() 中没有任何参数。

        • 在其中一个答案中,虽然我们将图例位置设置为none(因为colouraesthetics 内部,所以需要它)我们还有show.legend = F,这是多余的。

        • 您的colour 列已经是c("red", "green"),所以我们不需要使用scale_color

        【讨论】:

          猜你喜欢
          • 2021-02-07
          • 2013-02-17
          • 2019-09-10
          • 2023-03-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多