Boxplot schmoxplot: How to plot means and standard errors conditioned by a factor in R?

后端 未结 5 1173
孤独总比滥情好
孤独总比滥情好 2020-12-13 15:57

We all love robust measures like medians and interquartile ranges, but lets face it, in many fields, boxplots almost never show up in published articles, while means and sta

5条回答
  •  [愿得一人]
    2020-12-13 16:31

    Coming a little late to the game, but this solution might be useful for future users. It uses the diamond data.frame loaded with R and takes advantage of stat_summary along with two (super short) custom functions.

    require(ggplot2)
    
    # create functions to get the lower and upper bounds of the error bars
    stderr <- function(x){sqrt(var(x,na.rm=TRUE)/length(na.omit(x)))}
    lowsd <- function(x){return(mean(x)-stderr(x))}
    highsd <- function(x){return(mean(x)+stderr(x))}
    
    # create a ggplot
    ggplot(diamonds,aes(cut,price,fill=color))+
      # first layer is barplot with means
      stat_summary(fun.y=mean, geom="bar", position="dodge", colour='white')+
      # second layer overlays the error bars using the functions defined above
      stat_summary(fun.y=mean, fun.ymin=lowsd, fun.ymax=highsd, geom="errorbar", position="dodge",color = 'black', size=.5)
    

提交回复
热议问题