【问题标题】:R: ggplot reorder x-axis with facet_wrap and coord_flip [duplicate]R:ggplot用facet_wrap和coord_flip重新排序x轴[重复]
【发布时间】:2021-07-09 23:50:48
【问题描述】:

我有两个数据框,我想使用 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 轴,例如 here,但 我想使用相同的顺序一次完成所有这些对于所有地块。有谁知道如何在保持简单的同时做到这一点?

【问题讨论】:

    标签: r ggplot2 label facet-wrap x-axis


    【解决方案1】:

    您需要将x 转换为factor 并手动输入值。在这种情况下,由于您的轴已翻转,您需要将列表放入...已翻转。

    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() 
    

    【讨论】:

    • 哇哦——就是这么简单!非常感谢您指出这一点!
    猜你喜欢
    • 2018-05-14
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多