使用ggplot中的geom_smooth显示标准偏差

时间:2010-11-17 14:34:52

标签: r statistics ggplot2

我们有一些数据表示在不同情况下的许多模型运行。对于单个场景,我们希望显示平滑的平均值,填充区域代表特定时间点的标准偏差,而不是平滑的适合度。

例如:

d <- as.data.frame( rbind( cbind( 1:20, 1:20,1 ), cbind(1:20, -1:-20,2 ) ) )
names(d)<-c("Time","Value","Run")
ggplot( d, aes(x=Time,y=Value) ) + geom_line( aes(group=Run) ) + geom_smooth()

生成一个图表,其中表示两次运行,并且平滑均值,但即使运行之间的SD增加,平滑器的条保持相同的大小。我想让更平滑的环绕代表给定时间步的标准偏差。

考虑到许多不同的运行和输出变量,是否存在非劳动密集型的方法?

2 个答案:

答案 0 :(得分:16)

嗨,我不确定我是否正确理解你想要的东西,但是,例如,

d <- data.frame(Time=rep(1:20, 4), 
                Value=rnorm(80, rep(1:20, 4)+rep(1:4*2, each=20)),
                Run=gl(4,20))

mean_se <- function(x, mult = 1) {  
  x <- na.omit(x)
  se <- mult * sqrt(var(x) / length(x))
  mean <- mean(x)
  data.frame(y = mean, ymin = mean - se, ymax = mean + se)
}

ggplot( d, aes(x=Time,y=Value) ) + geom_line( aes(group=Run) ) + 
  geom_smooth(se=FALSE) + 
  stat_summary(fun.data=mean_se, geom="ribbon", alpha=0.25)

请注意,mean_se将出现在下一版本的ggplot2中。

答案 1 :(得分:0)

如果测量值在x上对齐/离散,则可接受的答案有效。如果数据连续,则可以使用滚动窗口并添加自定义功能区

iris %>%
    ## apply same grouping as for plot
    group_by(Species) %>%
    ## Important sort along x!
    arrange(Petal.Length) %>%
    ## calculate rolling mean and sd
    mutate(rolling_sd=rollapply(Petal.Width, width=10, sd,  fill=NA), rolling_mean=rollmean(Petal.Width, k=10, fill=NA)) %>%  # table_browser()
    ## build the plot
    ggplot(aes(Petal.Length, Petal.Width, color = Species)) +
    # optionally we could rather plot the rolling mean instead of the geom_smooth loess fit
    # geom_line(aes(y=rolling_mean), color="black") +
    geom_ribbon(aes(ymin=rolling_mean-rolling_sd/2, ymax=rolling_mean+rolling_sd/2), fill="lightgray", color="lightgray", alpha=.8) +
    geom_point(size = 1, alpha = .7) +
    geom_smooth(se=FALSE)

enter image description here