Show standard devation using geom_smooth and ggplot

后端 未结 2 591
野的像风
野的像风 2021-02-05 11:18

We have some data which represents many model runs under different scenarios. For a single scenario, we\'d like to display the smoothed mean, with the filled areas representing

2条回答
  •  南旧
    南旧 (楼主)
    2021-02-05 11:34

    The accepted answer just works if measurements are aligned/discretized on x. In case of continuous data you could use a rolling window and add a custom ribbon

    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)
    

提交回复
热议问题