Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 geom_bar fill aesthetic not changing

Tags:

r

ggplot2

I can't understand why I can't change the fill aesthetic for this geom_bar plot

# Reprex dataset

df <- structure(list(modality = c("Biological therapy", "Biological therapy", 
"Biological therapy", "Hormone treatment", "Chemotherapy", "Hormone treatment", 
"Biological therapy", "Biological therapy", "Hormone treatment", 
"Chemotherapy"), impact = c("Interrupted", "As planned", "Interrupted", 
"As planned", "As planned", "As planned", "Interrupted", "Interrupted", 
"As planned", "Interrupted")), row.names = c(NA, -10L), class = c("tbl_df", 
"tbl", "data.frame"))

This is top 10 rows of a larger dataframe (~2000) where I want to automatically count & plot proportions of modality and order by size of group (will be a side panel to a larger plot)

Plot function:

library(tidyverse)

bar <- df %>% 
  ggplot(aes(x = fct_rev(fct_infreq(modality)), 
             y = ..prop.., 
             group = 1), stat = 'count') +
  geom_bar(aes(fill = modality)) +
  theme_classic() +
  labs(x = NULL,
       y = '% Total') +
  scale_y_continuous(labels = scales::percent_format(accuracy = 1)) +
  scale_fill_viridis_d() +
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank()) +
  coord_flip()
bar

The viridis palette (or whatever I pass to fill) is not displayed. What am I missing?

like image 624
Brent Avatar asked Jan 18 '21 00:01

Brent


1 Answers

The issue was that you had the "group" aesthetic mapped to 1.

You can try this:

bar <- df %>% 
  ggplot(aes(y = modality,
             x = ..count../sum(..count..))) +
  geom_bar(aes(fill = modality)) +
  theme_classic() +
  scale_fill_viridis_d() +
  scale_x_continuous(name = "% Total", labels = scales::percent_format(accuracy = 1)) +
  scale_y_discrete(name = "", labels = NULL) +
  theme(axis.text.y = element_blank(),
        axis.ticks.y = element_blank())
  bar

enter image description here

like image 125
Eduardo Avatar answered Oct 31 '22 12:10

Eduardo