【问题标题】:How to correctly add average, standard deviation and jitter in geom_plot()? ggplot2如何在 geom_plot() 中正确添加平均值、标准差和抖动? ggplot2
【发布时间】:2021-03-17 14:47:43
【问题描述】:

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

我的代码(示例):

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

结果

【问题讨论】:

    标签: r ggplot2 geom-point


    【解决方案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 package (v0.3.0) 于 2021-03-17 创建

    【讨论】:

      猜你喜欢
      • 2021-06-04
      • 2020-12-26
      • 2018-02-25
      • 2012-04-20
      • 2014-03-21
      • 1970-01-01
      • 2017-01-18
      相关资源
      最近更新 更多