Search code examples
rggplot2gt

ggplot plots within a table


Problem

I would like to produce a good looking table which has ggplots within the cells of one column. One key element is that I would like to create a pdf output of this table eventually.

What I have tried so far

Hopefully the example below is understandable. Essentially I found that I can achieve what I want using the gt package. The problem is this creates a html widget which you then have to use phantomJS and webshot to export as a pdf.

library(dplyr)
library(purrr)
library(gt)
library(ggplot2)


dat = tibble(
  RowLabel = letters[1:5],
  Numeric = seq(100,500,100)
) %>% 
  mutate(
    plotData = RowLabel %>% map(function(pos){
      tibble(y=runif(10)*100) %>% 
        arrange(desc(y)) %>% 
        mutate(x=row_number())
    }),
    plot_obj = plotData %>% map(function(df){
      df %>%
        ggplot(aes(x=x,y=y))+
        geom_col()
    }),
    plot_grob = plot_obj %>% map(cowplot::as_grob)
  )


tab = dat %>% 
  select(RowLabel, Numeric) %>% 
  mutate(
    ggplot = NA
  ) %>% 
  gt() %>% 
  text_transform(
    locations = cells_body(vars(ggplot)),
    fn = function(x) {
      dat$plot_obj %>%
        map(ggplot_image, height = px(50))
    }
  )
tab

What do I want

I would like an output which is similar to the above example. However, I would like a solution which does not require me to use html widgets and can be saved directly as a pdf without the use of other programs. Is this possible to do using ggplot? I have started to learn more about grids/grobs/gtables etc but have not made any meaningful progress.

Thanks in advance!


Solution

  • Perhaps you could tweak the gtsave() function to suit? E.g.

    library(dplyr)
    library(purrr)
    library(gt)
    library(ggplot2)
    
    
    dat = tibble(
      RowLabel = letters[1:5],
      Numeric = seq(100,500,100)
    ) %>% 
      mutate(
        plotData = RowLabel %>% map(function(pos){
          tibble(y=runif(10)*100) %>% 
            arrange(desc(y)) %>% 
            mutate(x=row_number())
        }),
        plot_obj = plotData %>% map(function(df){
          df %>%
            ggplot(aes(x=x,y=y))+
            geom_col()
        }),
        plot_grob = plot_obj %>% map(cowplot::as_grob)
      )
    tab = dat %>% 
      select(RowLabel, Numeric) %>% 
      mutate(
        ggplot = NA
      ) %>% 
      gt() %>% 
      text_transform(
        locations = cells_body(vars(ggplot)),
        fn = function(x) {
          dat$plot_obj %>%
            map(ggplot_image, height = px(50))
        }
      )
    tab %>% 
      gt::gtsave(filename = "test.pdf", vwidth = 180, vheight = 250)
    

    (R v4.0.3 / gt v0.2.2)