使用ggplot2时如何更改箱线图的顺序? [英] How to change order of boxplots when using ggplot2?
问题描述
这个问题来自另一个一个.我无法在那里实施答案.
This question follows from this other one. I was unable to implement answers there.
定义:
df2 <- data.frame(variable=rep(c("vnu.shr","vph.shr"),each=10),
value=seq(1:20))
剧情:
require(ggplot2)
qplot(variable,value, data=df2,geom="boxplot")+
geom_jitter(position=position_jitter(w=0.1,h=0.1))
我希望以相反的顺序绘制箱线图(例如,一个在右在左,依此类推).
I would like to have the boxplots in the reverse order (e.g. one in right on left and so on).
我尝试了各种使用levels
、ordered
、relevel
、rev
等重新排序因子的方法,但我似乎无法正确理解语法.
I have tried various ways of reordering the factors using levels
, ordered
, relevel
, rev
and so on, but I simply cannot seem to get the syntax right.
推荐答案
你有没有试过这个:
df2$variable <- factor(df2$variable,
levels = c('vph.shr','vnu.shr'),ordered = TRUE)
我刚刚在那里挑选了一个订单,因为我的系统配置与我怀疑的您的略有不同,所以我的默认订单"可能会有所不同.但是你可以在指定它们时切换级别的位置.
I just picked an ordering there, since my system is configured slightly differently than yours I suspect, so my 'default ordering' may differ. But you can just switch the position of levels when specifying them.
其他一些选择,取决于您的口味:
A few other options, depend on your tastes:
为了反转当前的顺序:
factor(df2$variable,levels = rev(levels(df2$variable)),ordered = TRUE)
或者如果您不想手动输入每个级别,您可以使用子集来指定特定的顺序:
or you can use subsetting to specify a specific ordering if you don't want to type out each level by hand:
factor(df2$variable,levels = levels(df2$variable)[1:2],ordered = TRUE)
这篇关于使用ggplot2时如何更改箱线图的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!