根据 ggplot2 中类别的比例调整(堆叠)条形宽度
Adjusting (Stacked) Bar Width according to Proportions of Categories in ggplot2
我正在尝试根据类别的计数(或比例)更改我的(堆叠的)条形宽度,例如,我使用了钻石数据集。我想根据每个类别(变量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()
这给了我以下条形图:
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()
本质上,我自己计算比例而不是使用position = "fill"
,然后使用stat = identity
而不是stat = count
。
我正在尝试根据类别的计数(或比例)更改我的(堆叠的)条形宽度,例如,我使用了钻石数据集。我想根据每个类别(变量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()
这给了我以下条形图:
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()
本质上,我自己计算比例而不是使用position = "fill"
,然后使用stat = identity
而不是stat = count
。