如何在ggplot barplot中订购子组? [英] How to order subgroups in a ggplot barplot?
问题描述
我想在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
我希望将图例和条形图以北,南,东,西的顺序绘制出来。
我已经尝试添加 scale_fill_discrete(limits = c( north,south,east,west))
。它将图例按照期望的顺序排列,但不包括条形图(尽管条形图被重新排列)。
myplot + scale_fill_discrete(limits = c(北,南,东,西))
偶数如果我重新排序数据,我会得到与上面相同的结果:
mydata2 < - mydata [c(1,3, 4,2,5,7,8,6),]
width = 0.5,stat =identity)
myplot2< - ggplot(mydata2,aes(mygroup,value,fill = mysubgroup))+
geom_bar(position =dodge, )
myplot2 + scale_fill_discrete(limits = c(north,south,east,west
答案是让子组成为所需顺序的因子:
mydata < - data.frame(mygroup = c('A','A','A','A','B','B','B','B'),
mysubgroup = factor(c(north,west,south,east,
north,west,south,east),
等级= c(北,南,东,西)),
值= 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)
I would like to order the groups in both the legend and plot of a ggplot created with geom_bar.
Here is an example
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))
My starting point:
myplot <- ggplot(mydata, aes(mygroup, value, fill = mysubgroup)) +
geom_bar(position = "dodge", width = 0.5, stat = "identity")
myplot
I would like to have both the legend and the bars plotted in the order "north", "south", "east", "west".
I have tried adding scale_fill_discrete(limits = c("north", "south", "east", "west"))
to the plot. It puts the legend in the desired order, but not the bars (although the bars are rearranged).
myplot + scale_fill_discrete(limits = c("north", "south", "east", "west"))
even if I reorder the data, I get the same result as above:
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"))
I figured out the answer while writing the question (and will post as a CW to invite contributions)...
The answer is to have the subgroup be a "factor" with the levels in the desired order:
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")
这篇关于如何在ggplot barplot中订购子组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!