gpt4 book ai didi

r - 根据ggplot2中类别的比例调整(堆叠)条宽

转载 作者:行者123 更新时间:2023-12-01 13:21:01 29 4
gpt4 key购买 nike

我正在尝试根据类别的计数(或比例)更改我的(堆叠)条宽,作为示例,我使用了钻石数据集。我想根据每个类别(变量 cut )的频率看到不同的宽度。我首先创建了一个变量 cut_prop然后用下面的代码绘制

library(tidyverse)

cut_prop = diamonds %>%
group_by(cut) %>%
summarise(cut_prop = n()/nrow(diamonds))

diamonds = left_join(diamonds, cut_prop)

ggplot(data = diamonds,
aes(x = cut, fill = color)) +
geom_bar(aes(width=cut_prop), position = "fill") +
theme_minimal() +
coord_flip()

这给了我以下条形图:

enter image description here

R 给出了一个警告: Ignoring unknown aesthetics: width并且显然没有考虑条形宽度的类别比例,任何人都可以在这里帮助我?谢谢!

最佳答案

我认为这有效。从你离开的地方开始......

df <- diamonds %>% 
count(cut, color, cut_prop) %>%
group_by(cut) %>%
mutate(freq = n / sum(n)) %>%
ungroup

ggplot(data = df,
aes(x = cut, fill = color, y = freq, width = cut_prop)) +
geom_bar(stat = "identity") +
theme_minimal() +
coord_flip()

enter image description here

基本上,我自己计算比例而不是使用 position = "fill" ,然后使用 stat = identity而不是 stat = count .

关于r - 根据ggplot2中类别的比例调整(堆叠)条宽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49985971/

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