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

后端 未结 1 1355
北恋
北恋 2021-01-19 14:00

I want to plot a graph with the median of each row (not column!)(except values from the first column) with the standard deviation as errorbar. The result should look similar

相关标签:
1条回答
  • 2021-01-19 14:11

    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))
    
    0 讨论(0)
提交回复
热议问题