简体   繁体   中英

R Stackbar plot with Binary variables

I want to use ggplot, my data is as such

x <- c(TRUE,FALSE,FALSE,TRUE,TRUE,FALSE) #Logical
y <- c(0,1,1,0,1,0) #Numeric
dat <- data.frame(x,y)

I want to create a stacked barchart showing percentage...This seems like it should be an easy problem but somehow I'm getting this messed up and can't find a straight answer.

I've tried this

ggplot(data = dat, aes(x = x, y = y, fill = y))+geom_bar(position = 'fill', stat = 'identity')


ggplot(data = dat, aes(x = x, y = factor(y), fill = y))+geom_bar(position = 'fill', stat = 'identity')

The second one looks closer but the axis squashes everything to sum to 0?

Set position = 'stack' and the y-axis to the sum of y values, like this:

ggplot(data = dat, 
       aes(x = x, y = sum(y), fill = y)) +
       geom_bar(position = 'stack', stat = 'identity')

Hope you find it useful.

Try:

ggplot(data = dat, aes(x = x, fill = factor(y))) +
  geom_bar()

In particular, geom_bar() has a default for its aggregation to count up the rows ( stat = "count" ). You'd use stat = "identity" when you had already pre-calc'd the counts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM