34

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

假设这个结构的数据:

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

并运行代码:

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

产生这样的输出:

在此处输入图像描述

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

感谢帮助。

4

2 回答 2

33

EDIT Updated to ggplot2 0.9.3

Here's another solution. It uses facet_grid and space = "free"; also it uses geom_point() and geom_errorbarh(), and thus there is no need for coord.flip(). Also, the x-axis tick mark labels appear on the lower panel only. In the code below, the theme command is not essential - it is used to rotate the strip text to appear horizontally. Using the test dataframe from above, the following code should produce what you want:

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

The solution is based on the example on page 124 in Wickham's ggplot2 book.

于 2012-04-18T23:38:43.843 回答
27

使用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

产生:

在此处输入图像描述

编辑:我实际上认为我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
于 2012-04-17T00:07:29.927 回答