How to get a barplot with several variables side by side grouped by a factor

前端 未结 3 1805
日久生厌
日久生厌 2020-11-29 00:26

I have a dataset which looks like this one below. I am trying to make a barplot with the grouping variable gender, with all the variables side by side on the x axis (grouped

3条回答
  •  囚心锁ツ
    2020-11-29 01:04

    You can plot the means without resorting to external calculations and additional tables using stat_summary(...). In fact, stat_summary(...) was designed for exactly what you are doing.

    library(ggplot2)
    library(reshape2)            # for melt(...)
    gg <- melt(df,id="gender")   # df is your original table
    ggplot(gg, aes(x=variable, y=value, fill=factor(gender))) + 
      stat_summary(fun.y=mean, geom="bar",position=position_dodge(1)) + 
      scale_color_discrete("Gender")
      stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
                   color="grey80",position=position_dodge(1), width=.2)
    

    To add "error bars" you cna also use stat_summary(...) (here, I'm using the min and max value rather than sd because you have so little data).

    ggplot(gg, aes(x=variable, y=value, fill=factor(gender))) + 
      stat_summary(fun.y=mean, geom="bar",position=position_dodge(1)) + 
      stat_summary(fun.ymin=min,fun.ymax=max,geom="errorbar",
                   color="grey40",position=position_dodge(1), width=.2) +
      scale_fill_discrete("Gender")
    

提交回复
热议问题