R:ggplot使用镶嵌面环绕和坐标翻转对x轴重新排序

R:ggplot使用镶嵌面环绕和坐标翻转对x轴重新排序,r,ggplot2,label,facet-wrap,x-axis,R,Ggplot2,Label,Facet Wrap,X Axis,我有两个数据帧,我想使用facet_wrap将它们绘制在一起,如下所示: # create data frames d = data.frame( f = rep(c("f1", "f2"), each = 4), x = rep(c("a", "b", "c", "d"), 2), y = c(0, 2, 3, 3, 2, 1, 0

我有两个数据帧,我想使用facet_wrap将它们绘制在一起,如下所示:

# create data frames    
d = data.frame(
      f = rep(c("f1", "f2"), each = 4),
      x = rep(c("a", "b", "c", "d"), 2),
      y = c(0, 2, 3, 3, 2, 1, 0, 6))
    
# plot ggplot
ggplot(d, aes(x, y)) +
  geom_col() +
  facet_wrap(~ f) +
  coord_flip() 
结果是:

两个图都共享x轴,我将其翻转到一边。但是,x轴的顺序遵循字母顺序。这不是我想要的。相反,我想使用从上到下的顺序手动订购x轴:“a”、“c”、“d”、“b”

我试图通过以下代码对x轴值进行预排序,但这没有任何效果:

d2 = d[order(c("a", "a", "c", "c", "d", "d", "b", "b")),] 

ggplot(d2, aes(x, y)) +
  geom_col() +
  facet_wrap(~ f) +
  coord_flip() 

还有很多其他问题,人们希望使用不同的顺序分别对所有绘图的x轴进行重新排序,例如,但是我希望对所有绘图使用相同的顺序同时执行所有这些操作。有人知道如何在保持简单的同时做到这一点吗?

您需要将
x
转换为
因子
,然后手动输入值。在这种情况下,由于轴已翻转,因此需要将列表放入…翻转

library(tidyverse)

d = data.frame(
  f = rep(c("f1", "f2"), each = 4),
  x = rep(c("a", "b", "c", "d"), 2),
  y = c(0, 2, 3, 3, 2, 1, 0, 6))

d$x <- factor(d$x, levels= c('b','d','c','a'))

# plot ggplot
ggplot(d, aes(x, y)) +
  geom_col() +
  facet_wrap(~ f) +
  coord_flip() 
库(tidyverse)
d=数据帧(
f=代表(c(“f1”、“f2”),每个代表=4),
x=代表(c(“a”、“b”、“c”、“d”)、2),
y=c(0,2,3,3,2,1,0,6))

d$x噢,哇,就是这么简单!非常感谢你指出这一点!