如何使用因子级别的原始顺序来构造geom_bar

Ras*_*lam 0 r ggplot2 geom-bar

我有问题geom_bar在刻面时保持ggplot 图中的原始顺序.找到了一些在线帮助,但是当我试图解决时,它们没有用.

码:

df <- as.data.frame(cbind(x =rep(c("N-on", "N-off", "R-on", "R-off"),2),
            y = c(13,6,7,11,20,16,17,19), z = c(rep("A", 4), rep("B", 4))))
ggplot(data=df, aes(x=x, y=y)) +
  geom_bar(stat="identity") +
  facet_wrap(~ z, ncol =1) +
  coord_flip()
Run Code Online (Sandbox Code Playgroud)

输出: 在此输入图像描述

预期输出:垂直轴上的标签将按原始顺序排列,例如, "N-on", "N-off", "R-on", "R-off".

在此输入图像描述

jMa*_*hew 6

显然geom_bar是按因子参考水平的顺序绘制的

似乎订单保留在你的情节中,除了它自下而上.这似乎有效,

df$x <- factor(df$x, levels=rev(levels(df$x)))


ggplot(data=df, aes(x=x, y=y)) +
geom_bar(stat="identity") +
facet_wrap(~ z, ncol =1) +
coord_flip()
Run Code Online (Sandbox Code Playgroud)

  • 然后只需要`df $ x = factor(df $ x,levels = c("N-on","N-off","R-on","R-off"))`来获得你想要的订单.通常,将因子水平设置为您想要的任何顺序,这就是它们将被绘制的顺序. (4认同)