Monday, April 8, 2013

RG#38: Stacked bar chart (number and percent)

myd <- data.frame(   var1  = c(1,1,2,2,3,3,4,4),  
samp = c("A","B","A","B","A","B","A","B"),  
Value1 = c(3.5,2,5,8,3,2,7,2), Value2 = c(1.5,0,5,5,3,0,4,5) )
# rshaping data to long form for ggplot2
library(reshape2)
meltd<- melt(myd, id.vars=1:2)

#plot
library(ggplot2)
ggplot(meltd, aes(x=var1, y=value, fill=variable)) +
  geom_bar(stat="identity") + facet_grid(~samp) + theme_bw()

# stacked percent
library (scales) 
ggplot(meltd, aes(x=var1, y=value, fill=variable)) +
geom_bar(stat="identity", position = "fill") +
scale_y_continuous(labels = percent_format())+
   facet_grid(~samp) + theme_bw()



 

1 comment:

Note: Only a member of this blog may post a comment.