1

I want to add a table with some info that will be different in each panel within the facet. I'm using ggplot2 and facet_grid.

say I want to add some kind of descriptive statistics to each panel, and they not necessarily the same. these statistics are placed in a df I made for that purpose.

I found a few way to add these table to the graphs but:

  1. as far as I concern Annotate will give me the same table for all the panels in the facet.
  2. I would really like to use the facet_warp for the simplicity and not grid_extra...
library(datasets)
data(mtcars)
ggplot(data = mpg, aes(x = displ, y = hwy, color = drv)) +
    geom_point() +
    facet_wrap( ~ cyl,scales="free_y")

the place of the table is not that important to me, but I don't want it to overlap the graph.

My objective is kind of mixture between the two answers in that thread: Adding table to ggplot with facets

The first answers (with annotate-) won't work for me since I want the table in each of the plot to be unique.) The second answer is better, but I do not want it to overlap or hide some of the details in the graph, and in each panel the lines/scatters located in different place so I can't use it like that. I would like it to be attached just like in the annotate.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
letmetype
  • 105
  • 7
  • Possible duplicate of [Adding table to ggplot with facets](https://stackoverflow.com/questions/34625165/adding-table-to-ggplot-with-facets) – Jack Brookes Mar 25 '18 at 11:28

1 Answers1

3

try this

library(ggplot2)
library(tibble)
library(gridExtra)
library(grid)

GeomCustom <- ggproto(
  "GeomCustom",
  Geom,
  setup_data = function(self, data, params) {
    data <- ggproto_parent(Geom, self)$setup_data(data, params)
    data
  },

  draw_group = function(data, panel_scales, coord) {
    vp <- grid::viewport(x=data$x, y=data$y)
    g <- grid::editGrob(data$grob[[1]], vp=vp)
    ggplot2:::ggname("geom_custom", g)
  },

  required_aes = c("grob","x","y")

)

geom_custom <-  function(mapping = NULL,
           data = NULL,
           stat = "identity",
           position = "identity",
           na.rm = FALSE,
           show.legend = NA,
           inherit.aes = FALSE,
           ...) {
    layer(
      geom = GeomCustom,
      mapping = mapping,
      data = data,
      stat = stat,
      position = position,
      show.legend = show.legend,
      inherit.aes = inherit.aes,
      params = list(na.rm = na.rm, ...)
    )
}


gl <- list(tableGrob(iris[1:2,1:3]), 
           tableGrob(iris[1:4,1:3]),
           tableGrob(iris[1:3,1:3]),
           tableGrob(iris[1:2,1:2]))

dummy <- tibble(f=letters[1:4], grob = gl )

d <- tibble(x=rep(1:3, 4), f=rep(letters[1:4], each=3))

ggplot(d, aes(x,x)) +
  facet_wrap(~f) +
  theme_bw() +
  geom_custom(data=dummy, aes(grob=grob), x = 0.5, y = 0.5)