控制ggplot2 geom_bar的填充顺序和组 [英] Control the fill order and groups for a ggplot2 geom_bar
问题描述
library(ggplot2)
data <-
data.frame(
group=factor(c("a","c","b","b","c","a")),
x=c("A","B","C", "D","E","F"),
y=c(3,2,10,11,4,5))
> data
group x y
1 a A 3
2 c B 2
3 b C 10
4 b D 11
5 c E 4
6 a F 5
#And plot this:
ggplot(data)+
geom_bar(aes(x=x, y=y, fill=group, order=group),
stat="identity",
position="dodge")+
coord_flip()
这给出了一个图,其中x是根据因子水平绘制的:
This gives a figure where x is plotted according to factor levels:
但是如何根据group
变量的自定义顺序对x重新排序,并同时根据降序y
排列在group
内.例如,如果我要先绘制"c"(红色),然后再绘制"a"(绿色),然后再绘制"b"(蓝色),则x轴(x
变量)的绘制顺序为:E ,B,F,A,D,C.请注意,这可能与
But how can one reorder x according to a custom order of the group
variable and at the same time arrange within group
according to say descending y
. For instance if I want to plot first "c" (red), then "a" (green) and then "b" (blue) groups, the plot order of the x-axis (x
variable) would be: E, B, F, A, D, C. Note this may have resemblance to this SO question.
推荐答案
您首先需要在不使用factor
的情况下格式化数据框.然后,您需要将x列定义为factor
,但顺序取决于每个group
的最小y
.您需要在levels
参数中指定所需的特定顺序.
You need first to format your dataframe without factor
. Then you need to define the x column as factor
but with order depending on y
minimum per group
. This specific ordering you want needs to be specified in levels
argument.
我们在这里:
data <-
data.frame(
group=c("a","c","b","b","c","a"),
x=c("A","B","C", "D","E","F"),
y=c(3,2,10,11,4,5))
data$x = with(data, factor(x, levels=x[order(ave(y, group, FUN=min),y)]))
ggplot(data, aes(x, y, fill=group)) +
geom_bar(stat='identity', position='dodge') +
coord_flip()
这篇关于控制ggplot2 geom_bar的填充顺序和组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!