Search code examples
rggplot2facetggproto

Adding table to ggplot with facets


Reproducible code:

x = sample(1:12,100,replace=TRUE)
y = rnorm(100)
z = sample(c('Sample A','Sample B'),100,replace=TRUE)
d = data.frame(x,y,z)
ggplot(data=d, aes(factor(x),y)) + geom_boxplot() + stat_summary(fun.y=mean, geom="line", aes(group=1), color ='red') + 
  stat_summary(fun.y=mean, geom="point", color='red') + xlab('Months') + ylab('Metric') + facet_wrap(~z) 

I want to add a table at the end of this chart that displays the summary statistics- mean, median, quartiles and number of records for each month on the x-axis. I am not sure how this is possible for a facet layout. This is a simplified version of my chart and there are multiple facets I am working with. I am thinking along the lines of getting the statistics from stat_summary, which I can then display at the end?


Solution

  • Maybe you need to use grid library. Here's an example:

    library(ggplot2)
    
    x = sample(1:12,100,replace=TRUE)
    y = rnorm(100)
    z = sample(c('Sample A','Sample B'), 100, replace=TRUE)
    d = data.frame(x,y,z)
    
    g1 <- ggplot(data=d, aes(factor(x),y)) + 
      geom_boxplot() + 
      stat_summary(fun.y=mean, geom="line", aes(group=1), color ='red') + 
      stat_summary(fun.y=mean, geom="point", color='red') + 
      xlab('Months') +  ylab('Metric') +  facet_wrap(~z) 
    
    g2 <- ggplot() + theme_void() + xlim(0, 1) + ylim(0, 1) + 
      annotate("text", x=0.5, y=0.5, label="Draw the summary here")
    
    library(grid)
    
    grid.newpage()
    pushViewport(viewport(layout=grid.layout(4,2)))
    print(g1, vp=viewport(layout.pos.row = 1:3, layout.pos.col = 1:2))
    print(g2, vp=viewport(layout.pos.row = 4, layout.pos.col = 1))
    print(g2, vp=viewport(layout.pos.row = 4, layout.pos.col = 2))
    

    Result: enter image description here