简体   繁体   中英

ggplot2 geom_bar fill aesthetic not changing

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?

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

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM