如何在ggplot2中添加第二轴标签?

时间:2012-04-17 01:25:18

标签: r ggplot2

在我的previous question上构建我想在图的另一侧添加第二个轴标签。

数据框如下所示:

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

使用Tyler's solution,目前的图表如下:

enter image description here

以类似于森林图的方式,我想在表示图表值的第二组标签(我的数据框中的label变量)中添加,最好是在面板的右侧。所以这一切都模仿森林情节,类似于这个例子:

enter image description here

我知道第二轴seems to be frowned upon。然而,这些只是另一组标签..蚂蚁似乎是森林地块中的习俗。

我怎么能在ggplot中做到这一点?

1 个答案:

答案 0 :(得分:5)

编辑更新为ggplot2 0.9.3

将测试数据框中的标签集添加到分面图表非常简单。使用geom_text标签的美学,以及标签的x和y位置。在下面的代码中,xlim为标签创建了更多空间。以下代码:

library(gridExtra)
library(ggplot2)

p <- ggplot(test, aes(y = characteristic, x = es, xmin = ci_low, xmax = ci_upp)) + 
  geom_point() +   
  geom_errorbarh(height = 0) +
  geom_text(aes(label = label, x = 2, y = characteristic)) + 
  scale_x_continuous(limits = c(1, 2.2), breaks = c(1, 1.2, 1.4, 1.6, 1.8),
    labels=c("1.0", "1.2", "1.4", "1.6", "1.8")) +
  facet_grid(set ~ ., scales = "free", space = "free") +
  theme_bw() + 
  theme(strip.text.y = element_text(angle = 0),
    panel.grid.major = element_blank(),
    panel.grid.minor = element_blank())
p

grid.text(expression(paste("ES " %+-% " ci")), x = 0.78,   y = .92,
   gp = gpar(fontsize = 18))

产生

enter image description here