How to plot stacked proportional graph?
10,514
Using ggplot2
For ggplot2
and geom_bar
- Work in long format
- Pre-calculate the percentages
For example
library(reshape2)
library(plyr)
# long format with 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')
# note position = 'fill' would work with the value column
ggplot(xlong, aes(x = id, y = value, fill = variable)) +
geom_bar(stat = 'identity', position = 'fill', aes(fill = variable))
# will return the same plot as above
base R
A table object can be plotted as a mosaic plot. using plot
. Your x
is (almost) a table object
# get the numeric columns as a matrix
xt <- as.matrix(x[,2:4])
# set the rownames to be the first column of x
rownames(xt) <- x[[1]]
# set the class to be a table so plot will call plot.table
class(xt) <- 'table'
plot(xt)
you could also use mosaicplot
directly
mosaicplot(x[,2:4], main = 'Proportions')
Comments
-
Rachit Agrawal almost 2 years
I have a data frame:
x <- data.frame(id=letters[1:3],val0=1:3,val1=4:6,val2=7:9) id val0 val1 val2 1 a 1 4 7 2 b 2 5 8 3 c 3 6 9
I want to plot a stacked bar plot that shows the percentage of each columns. So, each bar represents one row and and each bar is of length but of three different colors each color representing percentage of val0, val1 and val2.
I tried looking for it, I am getting only ways to plot stacked graph but not stacked proportional graph.
Thanks.
-
Nishanth about 11 yearsdo you mean each bar should be of same length?
-
-
Rachit Agrawal about 11 yearsThanks. How do we change the width of the columns?? I have a lot of columns so, the column width are very small. Also how do we change the orientation of the X-axis labels.?
-
bdemarest about 11 yearsNote that
geom_bar()
accepts the argumentposition="fill"
which would allow you to skip theddply
step and use the melted data.frame directly.