val
val

Reputation: 1699

Plotting labels on bar plots with position = "fill" in R ggplot2

How does one plot "filled" bars with counts labels using ggplot2?

I'm able to do this for "stacked" bars. But I'm very confused otherwise.

Here is a reproducible example using dplyr and the mpg dataset

library(ggplot)
library(dplyr)

mpg_summ <- mpg %>%
  group_by(class, drv) %>%
  summarise(freq = n()) %>%
  ungroup() %>%
  mutate(total = sum(freq), 
         prop = freq/total)

g <- ggplot(mpg_summ, aes(x = class, y = prop, group = drv))
g + geom_col(aes(fill = drv)) +
  geom_text(aes(label = freq), position = position_stack(vjust = .5))

enter image description here

But if I try to plot counts for filled bars it does not work

g <- ggplot(mpg_summ, aes(x=class, fill=drv))
g + stat_count(aes(y = (..count..)/sum(..count..)), geom="bar", position="fill")  +
  scale_y_continuous(labels = percent_format())

enter image description here

Further, if I try:

g <- ggplot(mpg_summ, aes(x=class, fill=drv))
g + geom_bar(aes(y = freq), position="fill")  +
  geom_text(aes(label = freq), position = "fill") +
  scale_y_continuous(labels = percent_format())

I get:

Error: stat_count() must not be used with a y aesthetic.

Upvotes: 2

Views: 8063

Answers (1)

Brandon LeBeau
Brandon LeBeau

Reputation: 331

I missed the fill portion from the last question. This should get you there:

library(ggplot2)
library(dplyr)

mpg_summ <- mpg %>%
  group_by(class, drv) %>%
  summarise(freq = n()) %>%
  ungroup() %>%
  mutate(total = sum(freq), 
         prop = freq/total)

g <- ggplot(mpg_summ, aes(x = class, y = prop, group = drv))
g + geom_col(aes(fill = drv), position = 'fill') +
  geom_text(aes(label = freq), position = position_fill(vjust = .5))

enter image description here

Upvotes: 9

Related Questions