gpt4 book ai didi

使用stat ="count"时,geom_bar从高到低重新排序

转载 作者:行者123 更新时间:2023-12-03 15:36:06 32 4
gpt4 key购买 nike

我想在使用stat =“count”时将geom_bar图从高到低重新排序,以便可以应用填充。

我尝试使用geom_bar(aes(x = reorder(x,-stat(count)),fill = type),但是它不起作用并抛出错误“错误:stat_count需要以下缺失的美感:x”

library(ggplot2)
df <- data.frame(x = c("Bob", "James", "Mary", "Sally", "Timmy", "Sally", "Sally", "Bob", "Bob", "Mary"), type = c("A", "B", "A", "B", "B", "C", "B", "B", "A", "B"))
ggplot(df) +
geom_bar(aes(x = x, fill = type), stat = "count") +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

我希望条形从左数最高到右数最少。

最佳答案

我不确定 ggplot2 解决方案,但是我会使用 forcats 软件包解决此问题。有一个函数fct_infreq()可以按频率顺序设置因子水平。

然后,您可以执行以下操作:

ggplot(df) +
geom_bar(aes(x = forcats::fct_infreq(x), fill = type)) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

enter image description here

关于使用stat ="count"时,geom_bar从高到低重新排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56599684/

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