在R中的coord_flip之后反转订单 [英] Reversed order after coord_flip in R
问题描述
性别Sektion
1 m 5
2 m 5
3 w 3B
4 w 3B
5 w 3B
6 m 4
我有下面的图:
Sekplot < - ggplot(dbv,aes(x = Sektion,
fill = factor(gender),
stat =bin,
label = paste(round((.. count ..)/ sum(.. count ..)* 100), %)))
Sekplot< - Sekplot + geom_bar(position =fill)
Sekplot< - Sekplot + scale_y_continuous(labels = percent)
Sekplot< - Sekplot +实验室(title =test)
Sekplot < - Sekplot + scale_fill_discrete(name =test,breaks = c(m,w,kA),labels = c(m ,w,kA))
Sekplot< - Sekplot + geom_hline(aes(yintercept = ges,linetype =test),color =black,size = 0.75,show_guide = T)
Sekplot< - last_plot()+ coord_flip()
Sekplot< - Sekplot +指南(color = guide_legend(override.aes = list(linetype = 0)),
fill = guide_legend(override.aes = list(linetype = 0)),
shape = guide_legend(覆盖。 aes = list(linetype = 0)),
linetype = guide_legend())+ theme(legend.title = element_blank())
Sekplot
输出:
如何反转Sektion 轴?我想有一个在顶部,8个在底部。根据groupA $ Date< - factor(groupA $ Date,levels = rev(unique(groupA $ Date))),我试过了:$ /
Sekplot < - last_plot()+ coord_flip()+ scale_x_reverse()
有多种口味,但找不到正确的方式。
您可以使用 limits
参数添加 scale_x_discrete
来执行此操作。你可以简单地按照你想要的顺序写出限制,但是当你有很多因素级别时,这会变得复杂。相反,您可以从数据集中提取该因子的级别,并利用 rev
将其置于相反的顺序。
它看起来像:
scale_x_discrete(limits = rev(levels(dbv $ Sektion)))
Data example from dbv:
gender Sektion
1 m 5
2 m 5
3 w 3B
4 w 3B
5 w 3B
6 m 4
I have the following plot:
Sekplot <- ggplot(dbv,aes(x=Sektion,
fill=factor(gender),
stat="bin",
label = paste(round((..count..)/sum(..count..)*100), "%")))
Sekplot <- Sekplot + geom_bar(position="fill")
Sekplot <- Sekplot + scale_y_continuous(labels = percent)
Sekplot <- Sekplot + labs(title = "test")
Sekplot <- Sekplot + scale_fill_discrete(name="test", breaks=c("m", "w", "k.A."), labels=c("m", "w", "k.A."))
Sekplot <- Sekplot + geom_hline(aes(yintercept = ges, linetype = "test"), colour = "black", size = 0.75, show_guide = T)
Sekplot <- last_plot() + coord_flip()
Sekplot <- Sekplot + guides(colour = guide_legend(override.aes = list(linetype = 0 )),
fill = guide_legend(override.aes = list(linetype = 0 )),
shape = guide_legend(override.aes = list(linetype = 0 )),
linetype = guide_legend()) + theme(legend.title=element_blank())
Sekplot
Output:
Plot with y-axis in wrong order
How can I reverse the order of the "Sektion" axis? I'd like to have one on top and 8 at the bottom.
I tried, according to groupA$Date <- factor(groupA$Date, levels=rev(unique(groupA$Date))):
Sekplot <- last_plot() + coord_flip() + scale_x_reverse()
in several flavours, but couldn't find the right way.
You can add scale_x_discrete
with the limits
argument to do this. You could simply write out the limits in the order you want, but that gets complicated when you have many factor levels. Instead, you can pull the levels of the factor from your dataset and take advantage of rev
to put them in reverse order.
It would look like:
scale_x_discrete(limits = rev(levels(dbv$Sektion)))
这篇关于在R中的coord_flip之后反转订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!