【问题标题】:Setting an individual color palette for the group variable in geom_smooth为 geom_smooth 中的组变量设置单独的调色板
【发布时间】:2023-03-10 16:58:01
【问题描述】:

我有一个包含三组(在本例中为土壤样本)的数据集,每组都包含来自两个深度类别的测量值。我想为每个组使用相同的颜色,但深度不同的形状。我通过使用 Depths 进行着色和形状来实现这一点,然后结合图例。

但现在我想使用与 geom_point 相同的颜色设置一个额外的 geom_smooth。对于 geom_smooth,我需要将 group 参数设置为样本组(而不是深度),但我无法为 geom_smooth 设置新的 scale_col_manual。

df <- data.frame(X=runif(24, 0,1), Y=runif(24,80,100), Depth=as.factor(LETTERS[1:6]), 
                 Group=as.factor(LETTERS[1:3]))

labels <- c("A", "A", "B", "B", "C", "C")
library(ggplot2)

p1 <- ggplot(df, aes(X,Y,shape=Depth, col=Depth)) +
  geom_point() +
  scale_colour_manual(labels = labels ,
                      values = c("blue", "blue", "red", "red", "green", "green")) +   
  scale_shape_manual(labels = labels,
                     values = c(0,15,1,16, 2, 17))

p1

p1 + geom_smooth(aes(group=Group), method="lm", show.legend = F)

根据上面使用的颜色,geom_smooth 显示的回归线应该使用c("blue", "red", "green")。有什么方法可以实现吗?

【问题讨论】:

  • 我不确定我是否理解你的问题。这是你想要的吗:ggplot(df, aes(X,Y)) + geom_point(aes(shape=Depth, col=Depth)) + scale_colour_manual(labels = labels , values = c("blue", "blue", "red", "red", "green", "green")) + scale_shape_manual(labels = labels, values = c(0,15,1,16, 2, 17)) + geom_smooth(aes(fill=Group), method="lm", show.legend = F)
  • 这会使置信区间着色。我想给回归线上色。
  • 这个:ggplot(df, aes(X,Y)) + geom_point(aes(shape=Depth, col=Group)) + scale_colour_manual(values = c("blue", "red", "green")) + scale_shape_manual(labels = labels, values = c(0,15,1,16, 2, 17)) + geom_smooth(aes(group = Group, color=Group), method="lm", show.legend = FALSE) + guides(shape = guide_legend(override.aes = list(color = rep(c('blue', 'red', 'green'), each = 2))), color = FALSE)?
  • @mt1022 我也对如何做到这一点很感兴趣,而且很有效。
  • 谢谢。这按预期工作。您可能想将此作为答案发布。

标签: r ggplot2


【解决方案1】:

我们的目标似乎是按组着色点并根据深度给出不同的形状。

如果我们添加:

+ geom_smooth(aes(color=Group), method="lm", show.legend = F) 

会有两条蓝线,因为 OP 已手动设置色阶,前两个值使用两个蓝色。为了绕过,我们可以尝试:

ggplot(df, aes(X,Y)) + geom_point(aes(shape=Depth, col=Group)) +
    scale_colour_manual(values = c("blue", "red", "green")) +
    scale_shape_manual(labels = labels, values = c(0,15,1,16, 2, 17)) +
    geom_smooth(aes(group = Group, color=Group), method="lm", show.legend = FALSE) +
    guides(
        shape = guide_legend(
            override.aes = list(color = rep(c('blue', 'red', 'green'), each = 2))
        ),
        color = FALSE)

这样,点和颜色由同一个变量Group着色,所以不会有冲突。为了使形状具有相应的颜色,我们可以使用guide 覆盖其默认颜色。为了抑制点和线的颜色图例,我们必须在guides中添加color = FALSE

结果如下所示:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-15
    • 2016-10-21
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    • 1970-01-01
    • 2015-01-01
    相关资源
    最近更新 更多