好的,我们从获取数据表中的迷你图开始。这个Github issue 可能会有所帮助,并且提供了我认为比原始和流行的Combining data tables and sparklines 帖子更好的方法。
在数据表中添加迷你图
我将评论#### inline 以解释更改。
require(sparkline)
require(DT)
require(shiny)
require(tibble)
# create data
spark_data1<-tribble(
~id, ~label,~spark,
#### use sparkline::spk_chr helper
#### note spk_chr build for easy usage with dplyr, summarize
"a", c("C,D,E"),spk_chr(1:3,type="bar"),
"b", c("C,D,E"),spk_chr(3:1,type="bar")
)
ui <- tagList(
fluidPage(
DT::dataTableOutput("tbl")
),
#### add dependencies for sparkline in advance
#### since we know we are using
htmlwidgets::getDependency("sparkline", "sparkline")
)
server <- function(input, output) {
output$tbl <- DT::renderDataTable({
cb <- htmlwidgets::JS('function(){debugger;HTMLWidgets.staticRender();}')
dt <- DT::datatable(
as.data.frame(spark_data1),
rownames = FALSE,
escape = FALSE,
options = list(
#### add the drawCallback to static render the sparklines
#### staticRender will not redraw what has already been rendered
drawCallback = cb
)
)
})
}
shinyApp(ui = ui, server = server)
添加标签工具提示
我们会借鉴Github issue的经验做一个小辅助函数。
#### helper function for adding the tooltip
spk_tool <- function(labels) {
htmlwidgets::JS(
sprintf(
"function(sparkline, options, field){
return %s[field[0].offset];
}",
jsonlite::toJSON(labels)
)
)
}
一共
live example
require(sparkline)
require(DT)
require(shiny)
require(tibble)
#### helper function for adding the tooltip
spk_tool <- function(labels) {
htmlwidgets::JS(
sprintf(
"function(sparkline, options, field){
return %s[field[0].offset];
}",
jsonlite::toJSON(labels)
)
)
}
# create data
spark_data1<-tribble(
~id, ~spark,
#### use sparkline::spk_chr helper
#### note spk_chr build for easy usage with dplyr, summarize
"a", spk_chr(1:3,type="bar", tooltipFormatter=spk_tool(c("C","D","E"))),
"b", spk_chr(3:1,type="bar",tooltipFormatter=spk_tool(c("C","D","E")))
)
ui <- tagList(
fluidPage(
DT::dataTableOutput("tbl")
),
#### add dependencies for sparkline in advance
#### since we know we are using
htmlwidgets::getDependency("sparkline", "sparkline")
)
server <- function(input, output) {
output$tbl <- DT::renderDataTable({
cb <- htmlwidgets::JS('function(){debugger;HTMLWidgets.staticRender();}')
dt <- DT::datatable(
as.data.frame(spark_data1),
rownames = FALSE,
escape = FALSE,
options = list(
#### add the drawCallback to static render the sparklines
#### staticRender will not redraw what has already been rendered
drawCallback = cb
)
)
})
}
shinyApp(ui = ui, server = server)