[英]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是根据因子水平绘制的:
但是如何根据group
变量的自定义顺序对x进行重新排序,同时根据降序y
在group
内排列。 例如,如果我想首先绘制“c”(红色),然后是“a”(绿色)然后再绘制“b”(蓝色)组,则x轴( x
变量)的绘图顺序为:E,B ,F,A,D,C。注意这可能与这个 SO问题有相似之处。
您首先需要在没有factor
情况下格式化数据帧。 然后,您需要将x列定义为factor
但顺序取决于group
y
最小值。 您需要的特定顺序需要在levels
参数中指定。
开始了:
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.