r - 为 geom_smooth 中的组变量设置单独的调色板

标签 r ggplot2

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

但现在我想使用与 geom_point 相同的颜色设置一个额外的 geom_smooth。对于geom_smooth,我需要将组参数设置为样本组(而不是深度),但我无法为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")。有什么办法可以实现这一点吗?

最佳答案

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

如果我们添加:

+ 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

结果如下所示: enter image description here

关于r - 为 geom_smooth 中的组变量设置单独的调色板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44632457/

相关文章:

r - DPLYR 相当于多列的 n_distinct

r - 使用相对于另一个元素的动态位置/位置向 ggplot2 图中添加注释

r - 结合 coord_proj 和 geom_raster

r - 内插空间数据

r - seq_len(x) 总是比 1 快吗 :x in R? 一个比另一个更受欢迎吗?

r - xaringan 幻灯片分隔符不分离幻灯片

r - Knitr : automated figure numbering in the file names

r - 如何将数据框转换为热图格式?

r - 使 ggplot2 中的 geom_smooth() 适应观测数量

python - R(或Python)创建具有渐进分割的矩形 TreeMap