How to plot line with standard deviation of each row with ggplot

非 Y 不嫁゛ 提交于 2019-12-01 22:36:09

The code below creates a helper function to provide the median and sd values for plotting. We also transform the data to "long" format before plotting.

library(tidyverse)
theme_set(theme_bw())

df <- read.table(text=myTable, header = TRUE)
names(df) <- c("ID","Value1","Value2")

median_sd = function(x, n=1) {
  data_frame(y = median(x),
             sd = sd(x),
             ymin = y - n*sd,
             ymax = y + n*sd)
}

ggplot(df %>% gather(key, value, -ID), aes(ID, value)) +
  stat_summary(fun.data=median_sd, geom="errorbar", width=0.1) +
  stat_summary(fun.y=median, geom="line") +
  stat_summary(fun.y=median, geom="point") +
  scale_x_continuous(breaks=unique(df$ID))

You can avoid the helper function with the following code, but the function is handy to have around if you're going to do this a lot.

ggplot(df %>% gather(key, value, -ID), aes(ID, value)) +
  stat_summary(fun.y=median, fun.ymin=function(x) median(x) - sd(x), 
               fun.ymax=function(x) median(x) + sd(x), geom="errorbar", width=0.1) +
  stat_summary(fun.y=median, geom="line") +
  stat_summary(fun.y=median, geom="point") +
  scale_x_continuous(breaks=unique(df$ID))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!