Search code examples
rplotlyreactable

How to style embedded plotly plots as pseudo-sparklines?


The reactable packages supports embedded htmlwidgets. I can include plotly plots inside the cells, but I haven't been able to size them appropriately. I'd like for them to be very compact and fine-pointed like sparklines.

plot_ly(..., height = 50, width = 300) successfully shrinks the height of the figure, but the line strokes are heavy and the axis titles take up a lot of space. If I can make the figure more fine-pointed and completely remove the axis labels, maybe I could get there.

layout(xaxis = list(label = NULL)) does not remove the labels and I don't know how to read the documentation for the layout options. https://plotly.com/r/reference/#Layout_and_layout_style_objects

Any ideas are appreciated!

library(tidyverse)
library(reactable)
library(plotly)

dat <- mtcars |> 
  select(where(is.numeric)) |> 
  pivot_longer(everything()) |> 
  group_by(name) |> 
  summarize(plt = list(value))

my_plot <- function(value, ...) {
  tibble(value) |>
    plot_ly(type = "violin", x = ~value, width = 300, height = 50) |> 
    layout(autosize = TRUE, xaxis = list(label = NULL))
}

dat |> 
  reactable(
    columns = list(
      plt = colDef(cell = my_plot)
    )
  )

enter image description here


Solution

  • There are some minor issues with your code:

    1. set ~value to y
    2. if you want sparkling lines then use type= 'scatter' and mode = 'lines'
    3. Modify layout as you like

    Tweak your code like this:

    my_plot <- function(value, ...) {
      tibble(value) |>
        plot_ly(type = 'scatter', mode = 'lines', y = ~value, width = 300, height = 50) |> 
        layout(xaxis = list(showticklabels = FALSE, ticks = ''),
               margin = list(l = 1, r = 0, t = 0, b = 0))
    }
    

    enter image description here