如何在 ggplot2 R 中创建反应范数(按行加入)?

How to create a reaction norm (joining means by line) in ggplot2 R?

我有以下数据,我想在两个时间点 (t1, t2) 上绘制物种 1 和物种 2 的 "values"。我想创建一个图,其中使用 geom_points(不同颜色)可以看到每个物种的原始值。此外,我想使用更大尺寸的相同颜色来显示平均值。 对于给定的物种,我想连接 t1 和 t2 的平均值(也称为反应规范)。所以在这个例子中,物种1的线应该向上倾斜,而物种2的线应该保持不变。

我尝试了基本的 ggplot2,但我不知道如何添加线条并以更大的尺寸显示平均值。此外,由于某种原因 "fill" 没有生成不同的颜色。

time <- c("t1","t1","t1","t1","t1","t1","t2","t2","t2","t2","t2","t2")
species <- c(1,1,1,2,2,2,1,1,1,2,2,2)
value <- c(1,2,3,11,12,13,4,5,6,11,12,13)

df <- data.frame(time, species,value)
df$time <- as.factor(df$time)
df$species <- as.factor(df$species)

ggplot(df,aes(x=time, y=value, fill = species)) + 
  theme_bw() + 
  geom_point() + 
  stat_summary(fun.y=mean, position = "dodge") + 
  stat_summary(geom="errorbar", fun.data= mean_cl_boot, width = 0.1, size = 0.2, col = "grey57") + 
  ylab("Fitness") 

类似

ggplot(df,aes(x=time, y=value, color = species)) + # Change fill to color
  theme_bw() + 
  geom_point() + 
  stat_summary(fun.y=mean, position = "dodge") + 
  stat_summary(
    geom="errorbar", 
    fun.data= mean_cl_boot, 
    width = 0.1, size = 0.2, col = "grey57") + 
  # Lines by species using grouping
  stat_summary(aes(group = species), geom = "line", fun.y = mean) +
  ylab("Fitness")

如果你想要两个错误栏,你可以将行摘要的 group 添加到 ggplot 美学中。

如果我正在关注您想要获得的内容,那么这应该可以根据您的需要进行一些调整。基本技巧是在每一层中设置 aes。我在每个图层中单独设置 color/group,否则我很难让路径显示 between 次而不是 within次。

所以第一个总结就是组间路径。第二个是错误栏;正如我上面提到的,它有颜色,而不是填充。您之前在 aes 之外设置了颜色,无论您是否将颜色映射到变量,都会使错误栏全为灰色。平均点的大小 (4) 比常规点 (2) 大。

library(ggplot2)

ggplot(df, aes(x = time, y = value)) +
  stat_summary(aes(group = species), fun.y = mean, geom = "path") +
  stat_summary(aes(color = species), fun.data = mean_cl_boot, geom = "errorbar", width = 0.1) +
  stat_summary(aes(color = species), fun.y = mean, geom = "point", size = 4) +
  geom_point(aes(color = species), size = 2)

reprex package (v0.2.1)

创建于 2019-02-21