r - How to get a barplot with several variables side by side grouped by a factor -
i have dataset looks 1 below. trying make barplot grouping variable gender, variables side side on x axis (grouped gender filler different colors), , mean values of variables on y axis (which represents percentages)
tea coke beer water gender 14.55 26.50793651 22.53968254 40 1 24.92997199 24.50980392 26.05042017 24.50980393 2 23.03732304 30.63063063 25.41827542 20.91377091 1 225.51781276 24.6064623 24.85501243 50.80645161 1 24.53662842 26.03706973 25.24271845 24.18358341 2
in end want barplot
any suggestions how that? made searches find examples factors on x axis, not variables grouped factor. appreciated!
you can use aggregate calculate means:
means<-aggregate(df,by=list(df$gender),mean) group.1 tea coke beer water gender 1 1 87.70171 27.24834 24.27099 37.24007 1 2 2 24.73330 25.27344 25.64657 24.34669 2
get rid of group.1 column
means<-means[,2:length(means)]
then have reformat data in long format:
library(reshape2) means.long<-melt(means,id.vars="gender") gender variable value 1 1 tea 87.70171 2 2 tea 24.73330 3 1 coke 27.24834 4 2 coke 25.27344 5 1 beer 24.27099 6 2 beer 25.64657 7 1 water 37.24007 8 2 water 24.34669
finally, can use ggplot2 create plot:
library(ggplot2) ggplot(means.long,aes(x=variable,y=value,fill=factor(gender)))+ geom_bar(stat="identity",position="dodge")+ scale_fill_discrete(name="gender", breaks=c(1, 2), labels=c("male", "female"))+ xlab("beverage")+ylab("mean percentage")
Comments
Post a Comment