0

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.

writer_typer
  • 708
  • 7
  • 25

1 Answers1

4

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)
Leonardo
  • 2,439
  • 33
  • 17
  • 31
  • Looks promising, but this doesn't work with `factor(cyl)` I need the x axis to reflect that this is a factor instead of a continuous variable. – writer_typer Dec 15 '21 at 19:19
  • I updated my answer to have a factor(cyl) – Leonardo Dec 15 '21 at 19:38
  • Changing the second line to `geom_bar(aes(y = ..prop..), fill = "steelblue", stat = "prop") +` and the third line to `geom_text(aes(label = scales::percent(..prop..), y = ..prop.. ), stat= "prop", vjust = -.5)` worked, with this as the first line `ggplot(mtcars, aes(x = factor(cyl), by = 1)) +`. Can you update your answer with this and I'll accept it? – writer_typer Dec 15 '21 at 20:04
  • unfortunately with my version of `R` (4.1.2) and `ggplot2` (3.3.5) I get an error: `Can't find 'stat' called 'prop'`. If you tell me what versions of `R` and `ggplot2` you are using I can update the answer as you suggested. – Leonardo Dec 15 '21 at 20:17
  • 1
    I am using the `GGally` package to add 'prop'. I'm running the same versions as you are. – writer_typer Dec 15 '21 at 20:20
  • I have updated my answer! – Leonardo Dec 15 '21 at 20:23
  • 1
    Yay! Thanks Leonardo – writer_typer Dec 15 '21 at 20:38