Saurabh Kumar Karn Saurabh Kumar Karn - 1 year ago 90
R Question

How to draw stacked bargraph in ggplot for data type list?

I am trying to draw stacked bar graph for the data in R

alc sex count
<lgl> <fctr> <int>
1 FALSE Male 5537
2 FALSE Female 11555
3 TRUE Male 6989
4 TRUE Female 8150

I tried running this code :

ggplot(data = x_dat , aes(x = sex , y = count)) + geom_histogram()

Error: stat_bin() must not be used with a y aesthetic.`

I cant go any further. What am I doing wrong here ?

Answer Source

We can create a stacked barplot easily with base R

barplot(xtabs(count~alc + sex, x_dat), col = c("red", "blue"), legend = TRUE)


x_dat <- structure(list(alc = c(FALSE, FALSE, TRUE, TRUE), sex = c("Male", 
 "Female", "Male", "Female"), count = c(5537L, 11555L, 6989L, 
8150L)), .Names = c("alc", "sex", "count"), class = "data.frame",
row.names = c("1", "2", "3", "4"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download