[英]ggplot2, geom_bar, dodge, order of bars
I'd like to have ordered bars in dodge geom_bar
.我想在 dodge
geom_bar
订购酒吧。 Do you know how to deal with it?你知道如何处理吗?
My code:我的代码:
ttt <- data.frame(typ=rep(c("main", "boks", "cuk"), 2),
klaster=rep(c("1", "2"), 3),
ile=c(5, 4, 6, 1, 8, 7))
ggplot()+
geom_bar(data=ttt, aes(x=klaster, y=ile, fill=typ),
stat="identity", color="black", position="dodge")
And example plots to better understand the problem:和示例图以更好地理解问题:
What I have:我拥有的:
What I would like to have:我想要什么:
One option would be to make a new variable to represent the order the bars should be within each group and and add this variable as the group
argument in your plot.一种选择是创建一个新变量来表示条形图在每个组中的顺序,然后将此变量添加为绘图中的
group
参数。
Lots of ways to that task of making the variable, here's a way using function from dplyr .制作变量的任务有很多方法,这里有一种使用dplyr函数的方法。 The new variable is based on ranking
ile
in descending order within each klaster
group.新变量基于在每个
klaster
组内按降序排列ile
。 If you have ties in any group you'll want to figure out what you want to do in that case (what order should the bars be in given ties?).如果您在任何组中都有关系,您会想弄清楚在这种情况下您想做什么(条形在给定关系中的顺序应该是什么?)。 You may want to set the
ties.method
argument in rank
away from the default, probably to "first"
or "random"
.您可能需要设置
ties.method
在争论rank
从默认了,大概是"first"
或"random"
。
library(dplyr)
ttt = ttt %>%
group_by(klaster) %>%
mutate(position = rank(-ile))
ttt
Source: local data frame [6 x 5]
Groups: klaster [2]
typ klaster ile rank position
(fctr) (fctr) (dbl) (dbl) (dbl)
1 main 1 5 3 3
2 boks 2 4 2 2
3 cuk 1 6 2 2
4 main 2 1 3 3
5 boks 1 8 1 1
6 cuk 2 7 1 1
Now just add group = position
into your plot code.现在只需将
group = position
添加到您的绘图代码中。
ggplot() +
geom_bar(data=ttt, aes(x=klaster, y=ile, fill=typ, group = position),
stat="identity", color="black", position="dodge")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.