ggplot2geom_bar填充美学没有改变

我不明白为什么我不能改变这个 geom_bar 情节的填充美学

# 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"))

这是较大数据框(~2000)的前 10 行,我想在其中自动计算和绘制组的比例modality并按组大小排序(将是更大图的侧面板)

绘图功能:

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

viridis调色板(或任何我传递给fill未显示)。我错过了什么?

回答

问题是您将“组”美学映射到 1。

你可以试试这个:

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


以上是ggplot2geom_bar填充美学没有改变的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>