如何从ggplot2方面删除空因子?

rad*_*dek 17 r ggplot2

我试图通过根据因子变量引入构面来修改简单森林图的示例.

假设这个结构的数据:

test <- structure(list(characteristic = structure(c(1L, 2L, 3L, 1L, 2L
), .Label = c("Factor1", "Factor2", "Factor3"), class = "factor"), 
    es = c(1.2, 1.4, 1.6, 1.3, 1.5), ci_low = c(1.1, 1.3, 1.5, 
    1.2, 1.4), ci_upp = c(1.3, 1.5, 1.7, 1.4, 1.6), label = structure(c(1L, 
    3L, 5L, 2L, 4L), .Label = c("1.2 (1.1, 1.3)", "1.3 (1.2, 1.4)", 
    "1.4 (1.3, 1.5)", "1.5 (1.4, 1.6)", "1.6 (1.5, 1.7)"), class = "factor"), 
    set = structure(c(1L, 1L, 1L, 2L, 2L), .Label = c("H", "S"
    ), class = "factor")), .Names = c("characteristic", "es", 
"ci_low", "ci_upp", "label", "set"), class = "data.frame", row.names = c(NA, 
-5L))
Run Code Online (Sandbox Code Playgroud)

并运行代码:

p <- ggplot(test, aes(x=characteristic, y=es, ymin=ci_low, ymax=ci_upp)) + geom_pointrange() +
  coord_flip() + geom_hline(aes(x=0), lty=2) + 
  facet_wrap(~ set, ncol = 1) +
  theme_bw() + 
  opts(strip.text.x = theme_text())
Run Code Online (Sandbox Code Playgroud)

产生这样的输出:

在此输入图像描述

到目前为止都很好.但是,我想从我的下方面板中删除空的Factor3级别,但无法找到方法.有没有办法做到这一点?

感谢帮助.

San*_*att 23

编辑更新为ggplot2 0.9.3

这是另一种解决方案.它使用facet_gridspace = "free"; 它也使用geom_point()geom_errorbarh(),因此没有必要coord.flip().此外,x轴刻度线标签仅出现在下面板上.在下面的代码中,theme命令不是必需的 - 它用于旋转条带文本以水平显示.使用test上面的数据框,以下代码应该产生你想要的:

library(ggplot2)

p <- ggplot(test, aes(y = characteristic, x = es, xmin = ci_low, xmax = ci_upp)) +
   geom_point() +
   geom_errorbarh(height = 0) +
   facet_grid(set ~ ., scales = "free", space = "free") +
   theme_bw() +
   theme(strip.text.y = element_text(angle = 0))

p
Run Code Online (Sandbox Code Playgroud)

该解决方案基于Wickham的ggplot2书中第124页的示例.


Tyl*_*ker 14

用途scales = "free"如下:

p <- ggplot(test, aes(x=characteristic, y=es, ymin=ci_low, ymax=ci_upp)) + geom_pointrange() +
  coord_flip() + geom_hline(aes(x=0), lty=2) + 
  facet_wrap(~ set, ncol = 1, scales="free") +
  theme_bw() + 
  opts(strip.text.x = theme_text())

p
Run Code Online (Sandbox Code Playgroud)

哪个产生:

在此输入图像描述

编辑:我实际上认为我更喜欢drop = TRUE这个解决方案的论点,如:

p <- ggplot(test, aes(x=characteristic, y=es, ymin=ci_low, ymax=ci_upp)) + 
  geom_pointrange() +
  coord_flip() + geom_hline(aes(x=0), lty=2) + 
  facet_wrap(~ set, ncol = 1,  drop=TRUE) +
  theme_bw() + 
  opts(strip.text.x = theme_text())

p
Run Code Online (Sandbox Code Playgroud)

  • 我认为`space ="free"`是你正在寻找的另一个论点. (4认同)
  • 如何在不导致轴的比例扩大的情况下完成?在此示例中,请注意因素1和因子2网格线之间的空间在顶部和底部之间是不同的.这里并不是那么引人注目,但是在创建堆叠条形图时,根据轴中有多少因素掉落,条形面板之间的条形宽度现在会有很大差异.这个让我难过.有任何想法吗? (4认同)