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

浪尽此生 提交于 2019-12-02 00:16:50

问题


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 to that:

I have a dataframe like this:

myTable <- "
        1     -50     -52
        2     -44     -51
        3     -48     -50
        4     -50     -49
        5     -44     -49
        6     -48     -49
        7     -48     -49
        8     -44     -48
        9     -49     -48
       10     -48     -45
       11     -60     -48
       10     -50     -48
       11     -80     -47"
df <- read.table(text=myTable, header = TRUE)
df <- c("ID","Value1","Value2");

My data is stored in a .csv file, which I load with the following line:

df <- read.csv(file="~/path/to/myFile.csv", header=FALSE, sep=",")

回答1:


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))


来源:https://stackoverflow.com/questions/50495020/how-to-plot-line-with-standard-deviation-of-each-row-with-ggplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!