gpt4 book ai didi

r - ggplot2 geom_bar 填充美学没有改变

转载 作者:行者123 更新时间:2023-12-03 16:19:38 32 4
gpt4 key购买 nike

我不明白为什么我不能改变这个 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
enter image description here

关于r - ggplot2 geom_bar 填充美学没有改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65767429/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com