r - How to plot stacked proportional graph? -


i have data frame:

x <- data.frame(id=letters[1:3],val0=1:3,val1=4:6,val2=7:9)   id val0 val1 val2 1     1    4    7 2  b    2    5    8 3  c    3    6    9 

i want plot stacked bar plot shows percentage of each columns. so, each bar represents 1 row , and each bar of length of 3 different colors each color representing percentage of val0, val1 , val2.

i tried looking it, getting ways plot stacked graph not stacked proportional graph.

thanks.

using ggplot2

for ggplot2 , geom_bar

  1. work in long format
  2. pre-calculate percentages

for example

library(reshape2) library(plyr) # long format column of proportions within each id xlong <- ddply(melt(x, id.vars = 'id'), .(id), mutate, prop = value / sum(value))  ggplot(xlong, aes(x = id, y = prop, fill = variable)) + geom_bar(stat = 'identity') 

enter image description here

 # note position = 'fill' work value column  ggplot(xlong, aes(x = id, y = value, fill = variable)) +        geom_bar(stat = 'identity', position = 'fill', aes(fill = variable)) 

# return same plot above

base r

a table object can plotted mosaic plot. using plot. x (almost) table object

# numeric columns matrix xt <- as.matrix(x[,2:4]) # set rownames first column of x rownames(xt) <- x[[1]] # set class table plot call plot.table class(xt) <- 'table' plot(xt) 

enter image description here

you use mosaicplot directly

mosaicplot(x[,2:4], main = 'proportions') 

Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -