如何在geom_plot()中正确添加平均值、标准差和抖动?图表2

How to correctly add average, standard deviation and jitter in geom_plot()? ggplot2

我正在尝试创建一个图表来显示每个值(抖动)的平均值、标准偏差和点。但是,我无法插入平均点,所有类别的标准差都相同(这是不正确的)。

我的代码(示例):

# Package
library(ggplot2)

# Dataframe
fruit <- c()
value <- c()
for (i in 0:30) {
  list_fruit <- c('Apple','Banana','Pear')
  fruit <- append(fruit, sample(list_fruit, 1))
  value <-  append(value, sample(1:50, 1))
}
df <- data.frame(fruit, value)

# Seed
set.seed(123)

# Plot
ggplot(df, aes(x = fruit, y = value, color = fruit)) +
  geom_point() +
  geom_jitter(width = 0.1) + 
  geom_linerange(aes(ymin = mean(value)-sd(value), ymax = mean(value)+sd(value)), col = 'black') +
  scale_color_manual(values=c('red','blue','purple'))

结果

这可能是因为您所指的手册使用了旧版本的 ggplot2,该版本不允许数据的交替方向。例如 fun.y 现在称为 fun。以下是 ggplot2 版本 3.3.3 的示例。

# Package
library(ggplot2)

# Dataframe
fruit <- c()
value <- c()
for (i in 0:30) {
  list_fruit <- c('Apple','Banana','Pear')
  fruit <- append(fruit, sample(list_fruit, 1))
  value <-  append(value, sample(1:50, 1))
}
df <- data.frame(fruit, value)

# Seed
set.seed(123)

# Plot
ggplot(df, aes(x = fruit, y = value, color = fruit)) +
  geom_jitter(width = 0.1) + 
  stat_summary(
    geom = "linerange",
    fun.data = mean_sdl, 
    fun.args = list(mult = 1),
    colour = "black"
  ) +
  stat_summary(
    geom = "point",
    fun = mean,
    colour = "black", size = 3
  ) +
  scale_color_manual(values=c('red','blue','purple'))

reprex package (v0.3.0)

于 2021 年 3 月 17 日创建