insert ggplot barplot in table in R Shiny

936 views Asked by At

I wish to recreate a table like this where I insert a ggplot graph into a cell. I would like to use reactable to generate my table. desired_table

Any suggestions on how to proceed? I thought maybe I could use ggsave() to save the plot in png. I do not know however on to insert into a table.

Any assistance would be appreciated. thank you.

2

There are 2 answers

1
Tuco On BEST ANSWER

I had the same question myself, and the way I found is to create an htmlwidget with the ggplot inside it. Remember you can include any HTML widget in a reactable cell, that is what actually happens when using sparklines. So you can try something like this:

library(reactable)
library(ggplot2)
library(plotly)
library(dplyr)

data <- iris
#create a fake data with placeholders
data2 <-  data %>% group_by(Species) %>% summarise(Sepal.Length = unique(Species),
                                                   Sepal.Width = unique(Species),
                                                   Petal.Length = unique(Species),
                                                   Petal.Width = unique(Species))

reactable(data2, columns = list(
  Sepal.Length = colDef(cell = function(value){
    subDB <- data[data$Species==value,]
    p<-ggplotly(
      ggplot(subDB, aes(x=Sepal.Length))+geom_density() + xlab("")
    )
    return(p)
  }),
  Sepal.Width = colDef(cell = function(value){
    subDB <- data[data$Species==value,]
    p<-ggplotly(
      ggplot(subDB, aes(x=Sepal.Width))+geom_density() + xlab("")
    )
    return(p)
  }), 
  Petal.Length = colDef(cell = function(value){
    subDB <- data[data$Species==value,]
    p<-ggplotly(
      ggplot(subDB, aes(x=Petal.Length))+geom_density()+ xlab("")
    )
    return(p)
  }),
  Petal.Width = colDef(cell = function(value){
    subDB <- data[data$Species==value,]
    p<-ggplotly(
      ggplot(subDB, aes(x=Petal.Width))+geom_density()+ xlab("")
    )
    return(p)
  })
))

Note: As asked by @L Smeets since all of this are widgets variables the height and width are variable i.e. they adjust with the window. But we can control it if you want and have fixed height and width, both for the whole table by controlling the reactable or the ggplotly. To set the height and width of the ggplotly widget:

  Petal.Width = colDef(cell = function(value){
    subDB <- data[data$Species==value,]
    p<-ggplotly(
      ggplot(subDB, aes(x=Petal.Width))+geom_density()+ xlab(""),
      height = 100
    )
    return(p)
  })
1
Justin Landis On

So I don't think I've seen people put ggplots into cells for reactable. The below screen shot was taken from reactable examples. It seems that you may have to define an HTML widget or use one provided by the sparkline package.

enter image description here

Unfortunately, I do not know enough about html widgets yet to be of any more help.