Render datatable with sparklines in Shiny

这一生的挚爱 提交于 2019-11-30 23:34:31

I have modified your code to generate sparklines. I refered to this link to generate the sparklines.

require(sparkline)
require(DT)
require(shiny)

# create data
spark_data1<- data.frame(id = c('spark1', 'spark2'),
                          spark = c("1,2,3", "3,2,1"))



ui <- fluidPage(
  sparklineOutput("test_spark"),
  DT::dataTableOutput("tbl")
)

server <- function(input, output) {

  line_string <- "type: 'line', lineColor: 'black', fillColor: '#ccc', highlightLineColor: 'orange', highlightSpotColor: 'orange'"

  cd <- list(list(targets = 1, render = JS("function(data, type, full){ return '<span class=sparkSamples>' + data + '</span>' }")))

  cb = JS(paste0("function (oSettings, json) {\n  $('.sparkSamples:not(:has(canvas))').sparkline('html', { ", 
                 line_string, " });\n}"), collapse = "")

  output$tbl <- DT::renderDataTable({
    dt <-  DT::datatable(as.data.frame(spark_data1),  rownames = FALSE, options = list(columnDefs = cd,fnDrawCallback = cb))
  })
}

shinyApp(ui = ui, server = server)

Hope it helps!

Old-ish question, I know, but based on info in the question Add label to sparkline plot in datatable I think the solution is what you tried originally plus just a few lines. Here I trimmed out the parts demo-ing it works in the viewer and added just what is needed to make the sparklines work.

# dependencies
require(sparkline)
require(DT)
require(shiny)

# create data with sparklines
spark_data <- data.frame(
  id = c('spark1', 'spark2'),
  spark = c(
    spk_chr(values = 1:3, elementId = 'spark1'),
    spk_chr(values = 3:1, elementId = 'spark2')
  )
)

###  adding this <------------
cb <- htmlwidgets::JS('function(){debugger;HTMLWidgets.staticRender();}')

ui <- fluidPage(
  ###  and this <------------
  htmlwidgets::getDependency('sparkline'),
  dataTableOutput("tbl")
)

server <- function(input, output) {

  output$tbl <- renderDataTable(
    expr = spark_data,
    escape = FALSE,
    ###  and this <------------
    options = list(
      drawCallback =  cb
    )
  )
}

shinyApp(ui = ui, server = server)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!