gpt4 book ai didi

r - 如何在ggplot条形图中对子组进行排序?

转载 作者:行者123 更新时间:2023-12-01 01:09:02 28 4
gpt4 key购买 nike

我想对使用 geom_bar 创建的 ggplot 的图例和图中的组进行排序。

这是一个例子

mydata <- data.frame(mygroup = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'), 
mysubgroup = c("north", "west", "south", "east", "north", "west", "south", "east"),
value = c(5,10,6,12, 4, 4, 3, 5))

我的出发点:
myplot <- ggplot(mydata, aes(mygroup, value, fill = mysubgroup)) + 
geom_bar(position = "dodge", width = 0.5, stat = "identity")
myplot

enter image description here

我希望以“北”、“南”、“东”、“西”的顺序绘制图例和条形图。

我试过添加 scale_fill_discrete(limits = c("north", "south", "east", "west"))到情节。它按所需顺序放置图例,但不按条形排列(尽管条形已重新排列)。
myplot + scale_fill_discrete(limits = c("north", "south", "east", "west"))

即使我重新排序数据,我也会得到与上面相同的结果:
mydata2 <- mydata[c(1,3,4,2,5,7,8,6),]
myplot2 <- ggplot(mydata2, aes(mygroup, value, fill = mysubgroup)) +
geom_bar(position = "dodge", width = 0.5, stat = "identity")
myplot2 + scale_fill_discrete(limits = c("north", "south", "east", "west"))

enter image description here

最佳答案

我在写问题时想出了答案(并将作为 CW 发布以邀请贡献)...

答案是让子组成为具有所需顺序的级别的“因素”:

mydata <- data.frame(mygroup = c('A', 'A', 'A', 'A', 'B', 'B', 'B', 'B'), 
mysubgroup = factor(c("north", "west", "south", "east",
"north", "west", "south", "east"),
levels = c("north", "south", "east", "west")),
value = c(5,10,6,12, 4, 4, 3, 5))

ggplot(mydata, aes(mygroup, value, fill = mysubgroup)) +
geom_bar(position = "dodge", width = 0.5, stat = "identity")

关于r - 如何在ggplot条形图中对子组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16528065/

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