R

ggplot2 bar chart

# library

library(ggplot2)

 

# create a dataset

# the stupid thing is it needs to stored all values in one column for all stacked bars, instead of one column each bar

specie=c(rep("sorgho" , 3) , rep("poacee" , 3) , rep("banana" , 3) , rep("triticum" , 3) )  #rep is the for replicate

condition=rep(c("normal" , "stress" , "Nitrogen") , 4)  #4 bars and each bar has three groups

value=abs(rnorm(12 , 0 , 15))

data=data.frame(specie,condition,value)

 

# Grouped

#the dodge position means all bars sit next to each other. 

#If a Y value is given, it must use stat='identity' otherwise it defaults to use count or sth else, a bit like sas.

#the fill keyword specifies the group

ggplot(data, aes(fill=condition, y=value, x=specie)) +

    geom_bar(position="dodge", stat="identity")   

# Stacked

ggplot(data, aes(fill=condition, y=value, x=specie)) +

    geom_bar( stat="identity")    #without a position, it defaults to stacked bar chart

 

 

# Stacked Percent

ggplot(data, aes(fill=condition, y=value, x=specie)) +

    geom_bar( stat="identity", position="fill")

#add labels and use manual colors

ggplot(data, aes(fill=condition, y=value, x=specie)) +

    geom_bar( stat="identity") +

    scale_x_discrete(labels=c('a','b','d','e')) +

    scale_fill_manual(values=c("lightgreen", "tomato", "lightblue", "lightyellow"))