1

I have a plot doing bar plot for categorical variable (e.g. Group A, Group B, ...). I want to have multiple graphs on one page (something like this). I want to create a text outside the plot using:

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

It gave me an error "Error in non-numeric argument to binary operator". Since x axis is categorical variable, so I thought the error was caused by xmax, xmin values cannot be assigned to categorical data. So I used p1 = p + annotation_custom(grob = Text1,xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf). Again this same error.

I know how to do legend outside for multi-graph plot based on this reference: ggplot2: multiple plots with different variables in a single row, single grouping legend

The text outside example of Displaying text below the plot generated by ggplot2 is helpful. But this is for one graph, and I don't find it useful in my multi-graph plot situation.

Any idea about the reason of errors or how to position the annotation for multiple graphs one page with categorical x/y variables?

Community
  • 1
  • 1
enaJ
  • 1,565
  • 5
  • 16
  • 29

1 Answers1

0

Something like this, where you have a factor variable on the x axis and use the factor integers to position the text 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

lawyeR
  • 7,488
  • 5
  • 33
  • 63
  • Hi LawyeR, thank you for your quick response and help. My plot is more complex than the group bar, it has multiple graphs on one page and share one legend. something like: http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/ – enaJ Apr 23 '15 at 16:12
  • enaJ, do you want to put the text over the plots as a group, like a title for all the plots? Can you add to your question some reproducible data and your code for creating the plots, the code that triggered the error? – lawyeR Apr 23 '15 at 16:44
  • I want the text to be on the right side as annotation, not title. I have edited my question as you suggested. – enaJ Apr 23 '15 at 16:54