Home > Back-end >  How to change y axis from count to prop?
How to change y axis from count to prop?

Time:12-16

With ggplot2 and GGally, I created this bar chart with proportions:



enter image description here

ggplot(mtcars, aes(x = factor(cyl),  by = 1))  
  geom_bar(fill = "steelblue", stat = "prop")  
  geom_text(aes(label = scales::percent(after_stat(prop), accuracy = 1)), stat = "prop", nudge_y = 0.5)  
  theme_minimal()  
  theme(aspect.ratio = 1.5)

However, on the y axis, I would like to change that to reflect the percentages on the bars. I would like to avoid hard coding the values like ylim = "40", but let it use the values in the chart.

CodePudding user response:

Try this:

ggplot(mtcars, aes(x = cyl))   
  geom_bar(aes(y = ..prop..), fill = "steelblue", stat = "count")  
  geom_text(aes(label = scales::percent(..prop..), y = ..prop.. ), stat= "count", vjust = -.5)   
  ylim(0, 0.5)   
  ylab("")  
  theme_minimal()   
  theme(aspect.ratio = 1.5)

Edit: if you want a factor on x axis try

ggplot(mtcars, aes(x = factor(cyl)))   
  geom_bar(aes(y = (..count..)/sum(..count..)), fill = "steelblue", stat = "count")  
  geom_text(aes(label = scales::percent(round((..count..)/sum(..count..), 2)),
                y = ((..count..)/sum(..count..))), stat = "count", vjust = -.25)   
  ylim(0, 0.5)   
  ylab("")  
  theme_minimal()   
  theme(aspect.ratio = 1.5)

Edit2: with the GGally package you can use:

ggplot(mtcars, aes(x = factor(cyl), by = 1))  
  geom_bar(aes(y = ..prop..), fill = "steelblue", stat = "prop")  
  geom_text(aes(label = scales::percent(..prop..), y = ..prop.. ), stat = "prop", vjust = -.5)   
  ylim(0, 0.5)   
  ylab("")  
  theme_minimal()   
  theme(aspect.ratio = 1.5)
  • Related