library(DT)
library(sparkline)
library(dplyr)
library(tidyr)
library(htmlwidgets)
st_data <- ChickWeight %>%
mutate(cut_weight = as.numeric(cut(weight, c(0, 50, 100, 150, 200, 300) , labels = c(1:5)))) %>%
group_by(Chick, cut_weight) %>%
tally %>%
complete(cut_weight = c(1:5), fill = list(n = 0)) %>%
summarize(cut_weight = paste0(n, collapse = ","))
# Set column definitions
colDefs <- list(list(targets = 1, render = JS("function(data, type, full){ return '<span class=spark>' + data + '</span>' }")))
## JS options for the sparkline
bar_string <- "type: 'bar', width: 50, height: 25, barWidth: 20, barSpacing:5, highlightColor: 'orange', tooltipFormat: '{{offset:levels}} : {{value}}', tooltipValueLookups: { levels: { '0': '0-50', '1': '51-100', '2': '101-150', '3': '151-200', '4': '201-300' }}"
## JS construction of sparkline
sl_bar <- JS(sprintf("function (oSettings, json) { $('.spark:not(:has(canvas))').sparkline('html', {%s})}", bar_string))
sparktable <- datatable(st_data,
escape = FALSE,
rownames = FALSE,
options = list(
columnDefs = colDefs,
fnDrawCallback = sl_bar,
dom = 'ft'
)
)
## Add dependecy
sparktable$dependencies <- append(sparktable$dependencies, htmlwidgets:::getDependency("sparkline"))
sparktable
Notice the change in the size of sparkline compared to the first chunk
# Set column definitions
colDefs <- list(list(targets = 1, render = JS("function(data, type, full){ return '<span class=spark>' + data + '</span>' }")))
## JS options for the sparkline
bar_string2 <- "type: 'bar', barWidth: 20, barSpacing:5, highlightColor: 'orange', tooltipFormat: '{{offset:levels}} : {{value}}', tooltipValueLookups: { levels: { '0': '0-50', '1': '51-100', '2': '101-150', '3': '151-200', '4': '201-300' }}"
## JS construction of sparkline
sl_bar2 <- JS(sprintf("function (oSettings, json) { $('.spark:not(:has(canvas))').sparkline('html', {%s})}", bar_string2))
sparktable2 <- datatable(st_data,
escape = FALSE,
rownames = FALSE,
options = list(
columnDefs = colDefs,
fnDrawCallback = sl_bar2,
dom = 'ft'
)
)
## Add dependecy
sparktable2$dependencies <- append(sparktable2$dependencies, htmlwidgets:::getDependency("sparkline"))
sparktable2
## R version 3.3.2 (2016-10-31)
## Platform: x86_64-apple-darwin13.4.0 (64-bit)
## Running under: OS X El Capitan 10.11.6
##
## locale:
## [1] en_CA.UTF-8/en_CA.UTF-8/en_CA.UTF-8/C/en_CA.UTF-8/en_CA.UTF-8
##
## attached base packages:
## [1] stats graphics grDevices utils datasets methods base
##
## other attached packages:
## [1] htmlwidgets_0.7 tidyr_0.6.0 dplyr_0.4.3 sparkline_2.0
## [5] DT_0.2
##
## loaded via a namespace (and not attached):
## [1] Rcpp_0.12.7 digest_0.6.10 assertthat_0.1 R6_2.2.0
## [5] jsonlite_1.1 DBI_0.5-1 formatR_1.4 magrittr_1.5
## [9] evaluate_0.10 stringi_1.1.2 lazyeval_0.2.0 rmarkdown_1.1
## [13] tools_3.3.2 stringr_1.1.0 parallel_3.3.2 yaml_2.1.13
## [17] htmltools_0.3.5 knitr_1.14 tibble_1.2