Skip to content

adding ggplot graphs in every row of a table #152

@CerebralMastication

Description

@CerebralMastication

I can't quite get gt to render ggplot objects where each row in the table gets a different graph (like a spark line).

I can make a tibble where each row contains one cell that is the ggplot object, but I can't get text_transform and ggplot_image to convert that into an image:

library(tidyverse)
#> Warning: package 'tibble' was built under R version 3.5.2
library(gt)

# make a function for creating a plot
# of a group
plot_group <- function(name, df) {
  plot_object <-
    ggplot(data = df,
           aes(x = hp, y = trq,
               size = msrp)) +
    geom_point(color = "blue") +
    theme(legend.position = "none")
  return(plot_object)
}

# make a plot of each mfr
gtcars %>%
  group_by(mfr) %>%
  nest() %>%
  mutate(plot = map2(mfr, data, plot_group)) %>%
  select(-data) ->
  tibble_plot

# tibble plot contains 2 columns: 
#   mfr & plot where plot is a ggplot object

# can't figure out how to plot those ggplot objects though
tibble_plot %>%
  gt() %>%
  text_transform(
    locations = cells_data(vars(plot)),
    fn = function(x) {
      ggplot_image(x, height = px(200))
    }
  )
#> Error in UseMethod("grid.draw"): no applicable method for 'grid.draw' applied to an object of class "list"

it seems like maybe this should work... but it doesn't:

tibble_plot %>%
  gt() %>%
  text_transform(
    locations = cells_data(vars(plot)),
    fn = function(x) {
      ggplot_image(x$plot)
    }
  )

Thanks for taking a look at this!

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions