ggplot2将annotation_custom置于一个页面上的多个图表之外

时间:2015-04-22 16:07:17

标签: r plot annotations

我有一个绘图用于分类变量的条形图(例如A组,B组......)。我想在一个页面上有多个图形(类似this)。我想使用以下方法在图表外创建文本:

###### Plot three graphs together with one legend and one text on the right side

## this is the function that make one legend for multiple graphs
g_legend <- function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)}

mylegend <- g_legend(p3.legend)

### combine three graphs with legend     
p <- grid.arrange(arrangeGrob(p1 , p2 , p3, mylegend, ncol = 4, widths = c(20, 20, 20, 11)))  ## vertical 

### create text to put outside this multi-graph plot
Text1 = textGrob(paste("An example text"))    
p1 = p + annotation_custom(grob = Text1,  xmin = 1, xmax = 2, ymin = 20, ymax = 30)

它给了我一个错误“二进制运算符的非数字参数错误”。由于x轴是分类变量,所以我认为误差是由xmax引起的,xmin值不能分配给分类数据。所以我使用了p1 = p + annotation_custom(grob = Text1,xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf)。再次出现同样的错误。

基于此参考,我知道如何在多图绘图外做传奇: ggplot2: multiple plots with different variables in a single row, single grouping legend

Displaying text below the plot generated by ggplot2示例之外的文字很有帮助。但这是针对一个图表,我发现在我的多图情节中它并没有用。

有关错误原因或如何将多个图表的注释定位到一个具有分类x / y变量的页面的任何想法?

1 个答案:

答案 0 :(得分:0)

像这样的东西,你在x轴上有一个因子变量,并使用因子整数来定位文本grob?

require(ggplot2)
df <- data.frame(a = seq(0, 30, 6), group = as.factor(c("a", "b", "c", "d", "e", "f")))

Text1 <- textGrob("Test text")
ggplot(data = df, aes(x = group, y = a)) + 
  geom_bar(stat = "identity") +
  annotation_custom(grob = Text1,  xmin = 2, xmax = 3, ymin = 20, ymax = 22)

enter image description here