I have got a reference by leonawicz that can combine sparkline and DT perfectly(Many thanks for him). But, could you please give me a help to make a composited sparkline? Thanks a lot!.
Here is the sample code
library(data.table)
library(DT)
library(sparkline)
Data <- data.table(Type = c("A", "B", "C"),
Value_1 = c("1,1,2,2", "2,2,3,3", "3,3,4,4"),
Value_2 = c("0,1,2,3", "2,3,4,5", "4,5,6,7"))
r <- c(0, 8)
line_string <- "type: 'line', lineColor: 'black', fillColor: '#ccc',
highlightLineColor: 'orange', highlightSpotColor: 'orange',
width: 80,height: 60"
cb_line = JS(paste0("function (oSettings, json) {
$('.spark:not(:has(canvas))').sparkline('html', { ",
line_string, ", chartRangeMin: ", r[1], ", chartRangeMax: ",
r[2], " }); }"), collapse = "")
cd <- list(list(targets = 1:2, render = JS("function(data, type, full){
return '<span class=spark>' + data + '</span>' }")))
d1 <- datatable(Data, rownames = FALSE, options = list(columnDefs = cd,
fnDrawCallback = cb_line))
d1$dependencies <- append(d1$dependencies,
htmlwidgets:::getDependency("sparkline"))
d1
How could composite Value_1 and Value_2 into 1 sparkline chart? Thank you again!
First of all you are making it difficult on yourself. What you achieved with all that JS code can be easily reproduced in a more
R
way using the functionssparkline
gives us (you are literally not using thesparkline
package at all if not for adding the dependency):Data:
The data you are using doesn't make much sense to me. It should be organized in a tidier way (one variable per column, one observation per row).
So I converted it:
Simple sparklines
sparkline
plays nicely withdplyr
, and in particularsummarize
.The function
spk_char
convert the htmlwidget to a string that can be used inside another widget, in this casedatatable
. Options can be specified directly, no need to useJS
.Composite sparklines
That said, combining the two
sparklines
has proved more difficult than I thought it would be. The solution is quite easy, but finding it took a bit.What I did is:
spk_composite
DT
usingas.character(as.tags(l))
The last step is what is done internally by
spk_chr
.