【问题标题】:How to change the order of facet labels in ggplot (custom facet wrap labels)如何更改 ggplot 中分面标签的顺序(自定义分面包装标签)
【发布时间】:2011-03-30 18:37:24
【问题描述】:

我使用ggplot 绘制了一个平面图,这是该图

我遇到的问题是,构面(标签)按字母顺序排序(例如:E1、E10、E11、E13、E2、E3、I1、I10、I2)但我需要它们是像 E1 这样的自定义顺序, I1、E2、I2、E3、E10、I10、E11、E13。

我该怎么做?

【问题讨论】:

  • 重新排列基础因子的顺序。您可以使用relevel()reorder() 或进行自定义订单并使用factor()
  • 这能回答你的问题吗? Fixing the order of facets in ggplot

标签: r ggplot2


【解决方案1】:

如果您提供的分组变量不是因素,则不要依赖factor()ggplot 内部强加的默认级别顺序。自己明确设置级别。

dat <- data.frame(x = runif(100), y = runif(100), 
                  Group = gl(5, 20, labels = LETTERS[1:5]))
head(dat)
with(dat, levels(Group))

如果我希望它们以这种任意顺序怎么办?

set.seed(1)
with(dat, sample(levels(Group)))

为此,请按照您想要的方式设置关卡。

set.seed(1) # reset the seed so I get the random order form above
dat <- within(dat, Group <- factor(Group, levels = sample(levels(Group))))
with(dat, levels(Group))

现在我们可以使用它来按照我们想要的顺序绘制面板:

require(ggplot2)
p <- ggplot(dat, aes(x = x)) + geom_bar()
p + facet_wrap( ~ Group)

产生:

【讨论】:

  • 同上,但如果数据本身已经在自定义顺序中,您希望 Group 变量在其中,并且您不想按该顺序手动创建向量:dat &lt;- within(dat, Group &lt;- factor(Group, levels = unique(levels(Group))))因为unique 保留了订单
【解决方案2】:

只是在处理类似的问题。默认情况下,我的关卡如下所示:

 [1] "A1"  "A10" "A2"  "A3"  "A4"  "A5"  "A6"  "A7"  "A8"  "A9" 
[11] "B1"  "B2"  "B3"  "B4"  "B5"  "B6"  "B7"  "B8"  "B9" 

请注意,由于字母顺序,第二级不合适。

这是我正在做的修复订单:

reorder(factor(fct),
        fct %>%
          str_replace("([[:alpha:]]+)", "\\1|") %>%
          str_split("\\|") %>%
          sapply(function(d) sprintf("%s%02d", d[1], as.integer(d[2]))),
        function(x) x[1])

它将“A1”等级别替换为“A01”,然后根据这些级别重新排序。我相信您可以更有效地执行此操作,但它确实可以完成这项工作。

它可以被改编以解决最初的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多