0

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.