Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proportion with ggplot geom_bar [duplicate]

Tags:

r

ggplot2

What is the simplest way to do with ggplot the same as done here:

enter image description here

Do I need call prop.table or maybe there is a simplier way?

REPRODUCTABLE EXAMPLE:

x <- c("good", "good", "bad", "bad", "bad", "bad", "perfect", "perfect", "perfect")
y <- c("exercise1", "exercise2", "exercise3", "exercise1", "exercise2", "exercise3", "exercise1", "exercise2", "exercise3")
dt <- data.frame(x, y)

ggplot(dt, aes(x, fill = y)) + geom_bar()
like image 556
W W Avatar asked Oct 27 '17 22:10

W W


1 Answers

This is a similar question to this previous one here. You can use the position = "fill" argument within ggplot to scale bars to 100% height. The scale_y_continuous(labels = scales::percent) command changes the frequency scale from 0-1 to 0-100%.

library(ggplot2)

x <- c("good", "good", "bad", "bad", "bad", "bad", "perfect", "perfect", "perfect") 
y <- c("exercise1", "exercise2", "exercise3", "exercise1", "exercise2", "exercise3", "exercise1", "exercise2", "exercise3") 
dt <- data.frame(x, y)

# Build plot
ggplot(dt, aes(x, fill = y)) +
  geom_bar(position = "fill") +
  scale_y_continuous(labels = scales::percent)

enter image description here

like image 156
Michael Harper Avatar answered Sep 26 '22 03:09

Michael Harper