gpt4 book ai didi

r - 每个方面的总和百分比 - 尊重 "fill"

转载 作者:行者123 更新时间:2023-12-03 22:28:10 26 4
gpt4 key购买 nike

我正在尝试创建一个分面条形图,每个分面的百分比加起来为 100。对此的解决方案似乎是 group 的组合和 ..density.. .如何 - 在我看来 groupfill 冲突.

数据:

test <- data.frame(
test1 = sample(letters[1:2], 100, replace = TRUE),
test2 = sample(letters[3:8], 100, replace = TRUE)
)

这使百分比正确:
ggplot(test, aes(test2)) +
geom_bar(aes(y = ..density.., fill=test2,group=test1)) +
facet_grid(~test1)

巴士如你所见, fill被覆盖:
percentage sums to 100 for each facet

但是,下面的代码尊重 fill但给了我错误的百分比(整个图表的总和为 100)(使用..密度..):
ggplot(test, aes(test2)) +
geom_bar(aes(y = ..count../sum(..count..), fill=test2)) +
facet_grid(~test1)

percentage sums to 100 for the total chart

相关:我的这个老问题: percentage on y lab in a faceted ggplot barchart? .

是的 - 我可以创建额外的数据,但我觉得这属于表示层。其实这感觉像一个错误?

最佳答案

这有点小技巧,但您可以引用 ..x..geom_bar称呼。唯一的问题是ggplot考虑这个 numeric所以我在给 scale_fill_brewer 的电话中被迫考虑并给出了很好的标签。

ggplot(test, aes(x= test2, group = test1)) + 
geom_bar(aes(y = ..density.., fill = factor(..x..))) +
facet_grid(~test1) +
scale_fill_brewer(name = 'test2', breaks = 1:6,
labels = levels(test$test2), palette = 'Set3')

enter image description here

与不强制比较 ..x..到一个因素
ggplot(test, aes(x= test2, group = test1)) + 
geom_bar(aes(y = ..density.., fill = ..x..)) +
facet_grid(~test1)

enter image description here

关于r - 每个方面的总和百分比 - 尊重 "fill",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12236160/

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