0

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

我的代码(示例):

# 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'))

结果 在此处输入图像描述

4

1 回答 1

1

这可能是因为您所指的手册使用的是旧版本的 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 包(v0.3.0)于 2021-03-17 创建

于 2021-03-17T15:00:36.213 回答