首页 > 解决方案 > 有没有办法在 r 中的 ggplot 中向几何线添加标准误差线?

问题描述

这是对先前在此处回答的问题的后续:Plotting values in ggplot over time by group,条件是一组是平均值的一条线,另一组是 R 中的单独线

我有一个数据集,我想为每条线每年的治疗率添加标准误差线。我想修改下面的代码以在 geom = "line" 之前包含 " geom = "errorbar" 但得到以下错误: stat_summary 中的错误(data = ~subset(., Intervention == 0), aes(group = - 1), : 由多个实际参数匹配的形式参数“geom”。

有没有不同的方法来修改它?提前谢谢你的帮助。

样本数据:

library(ggplot2)

set.seed(1234)

states <- rownames(USArrests)
intervened <- sample(states, 10)

df <- expand.grid(year = 2010:2015, state = states)
df$Intervention <- as.numeric(df$state %in% intervened)
df$rate <- cumsum(rnorm(nrow(df)))
head(df)
#>   year   state Intervention      rate
#> 1 2010 Alabama            0 -0.574740
#> 2 2011 Alabama            0 -1.121372
#> 3 2012 Alabama            0 -1.685824
#> 4 2013 Alabama            0 -2.575862
#> 5 2014 Alabama            0 -3.053054
#> 6 2015 Alabama            0 -4.051441
ggplot(df, aes(x = year, y = rate, group = state)) +
  geom_line(
    data = ~ subset(., Intervention == 1),
    aes(colour = state)
  ) +
  stat_summary(
    data = ~ subset(., Intervention == 0),
    aes(group = -1),
    fun.data = mean_se,
    geom = "line", size = 2
  )

标签: rggplot2

解决方案


推荐阅读