gpt4 book ai didi

r - 在 ggplot2 中对多个变量进行排序

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

我试图在变量中对变量进行分组并按降序排序。

mydf

region  airport value
MIA FLL 0.244587909
MIA PBI 0.824144687
MIA MIA 0.484907626
NYC EWR 0.731075565
NYC LGA 0.708648915
NYC HPN 0.523991258
LAX LGB 0.651847818
LAX LAX 0.423607479
LAX SNA 0.433837044
LAX ONT 0.723144957
Other MCO 0.657586674
Other SJC 0.084138321
Other OAK 0.698794154
Other BOS 0.85765002
Other BNA 0.018953126
Other WAS 0.234897245

/image/G1E2k.jpg

enter image description here

我正在尝试重现上面的图表。

这是第一次尝试:
ggplot(mydf, aes(x=airport,y=value, fill = region)) +  
geom_bar(stat = "identity")

这是第二次尝试:
ggplot(mydf, aes(x=reorder(airport,-value,sum),y=value, fill = region)) +  
geom_bar(stat = "identity")

我被困在这里。我可以嵌套重新排序吗? reorder(reorder(x, y), y)我不想让这成为一个手动调用每个分组的过程。

This is as far as I can get
mydf$order <- c('ONT','LGB','SNA','LAX','PBI','MIA','FLL','EWR','LGA','HPN','BOS','OAK','MCO','WAS','SJC','BNA')

ggplot(mydf, aes(x=airport,y=value, fill = region, order = order)) +
geom_bar(stat = "identity")

这仍然不起作用。我很感激任何帮助!

最佳答案

@eipi10 有一个很好的答案,但我经常发现自己需要这样做,再加上一些其他变量的方面,所以还有其他选项以及使用 forcats包裹:

require(dplyr)
require(forcats)

mydf %>%
mutate(ordering = -as.numeric(region) + value,
airport = fct_reorder(airport, ordering, .desc = T)) %>%
ggplot(aes(airport, value, fill = region)) + geom_col()

enter image description here

这是我可能需要如何同时使用排序和构面的示例,我在其中添加了 + facet_grid(~fac, scales = "free_x", space = "free_x")另一个名为“fac”的专栏包含我的旅行历史:

enter image description here

关于r - 在 ggplot2 中对多个变量进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43877663/

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