How do I add conditional fractions to geom_tile?

Viewed 316

I'm comparing two categorical variables in the Carseats data.

Initialize the dataset

library('ISLR')
data(Carseats)
attach(Carseats)

Plot the viz

Carseats %>% 
  count(ShelveLoc, Urban) %>%  
  ggplot(mapping = aes(x = ShelveLoc, y = Urban)) +
  geom_tile(mapping = aes(fill = n)) + 
  geom_text(colour = "white",aes(label=paste(round((n/sum(n)*100)),"%",sep=""))) + 
  geom_text(colour = "white", nudge_y = .1, aes(label=paste(n))) + 
  geom_text(colour = "white", nudge_y = -.1, aes(label=n))

That gets me this -->

enter image description here

I'd like the third value to show the percent by class.

The bottom right would show the result from this equation

68 (count that is medium and no) / 118 (count that is no)

The top right would show the result from this equation

151 (count that is medium and yes) / 282 (count that is yes)

1 Answers

Is this what you are looking for?

Carseats %>% 
  count(ShelveLoc, Urban) %>%
  group_by(Urban) %>%
  mutate(yes_no_pct = round(n / sum(n) * 100)) %>%
  ungroup() %>%
  ggplot(mapping = aes(x = ShelveLoc, y = Urban)) +
  geom_tile(mapping = aes(fill = n)) + 
  geom_text(colour = "white", aes(label = paste0('Percent of Total: ', round((n / sum(n) * 100)), '%'))) + 
  geom_text(colour = "white", nudge_y = .1, aes(label = paste0('Count: ', n))) + 
  geom_text(colour = "white", nudge_y = -.1, aes(label = paste0('Percent of Group: ', yes_no_pct, '%'))) +
  theme_minimal()

enter image description here

Related