ggplot graphing proportions within multiple catego

2019-08-31 07:59发布

问题:

I am trying to graph true/false proportions for data with multiple groupings. Specifically, I want to see the true/false proportions for data column c which can be grouped by true/false data from a and b.

a = sample(c(TRUE, FALSE), 50, replace=TRUE)
b = sample(c(TRUE, FALSE), 50, replace=TRUE)
c = sample(c(TRUE, FALSE), 50, replace=TRUE)
df = as.data.frame(cbind(a,b,c))

I tried this:

ggplot(df,aes(x = a, fill = c)) + 
    geom_bar(position = "fill")

But I don't know how to implement the true/false data from B into the graph. Essentially I want 4 c proportions: A/B = False/False, False/True, True/False, True/True

http://i.stack.imgur.com/HhtHZ.png

This is essentially the graph I want, except time=A, sex=B, and total_bill=proportion of true/false for c

回答1:

Here is one approach using dplyr.

library(dplyr)
library(ggplot2)

set.seed(111)
a = sample(c(TRUE, FALSE), 50, replace=TRUE)
b = sample(c(TRUE, FALSE), 50, replace=TRUE)
c = sample(c(TRUE, FALSE), 50, replace=TRUE)
df = as.data.frame(cbind(a,b,c))

UPDATED

Given the comments of the OP, here is a revised version.

foo <- group_by(df, a, b, c) %>% 
       summarise(total = n()) %>%
       mutate(prop = total / sum(total))

# Draw a ggplot figure      
ggplot(foo, aes(x = a, y = prop, fill = b)) +
geom_bar(stat = "identity", position = "dodge")



标签: r ggplot2