sparkline R创建html表

时间:2015-09-17 15:44:48

标签: html r charts sparklines

我找到了包sparklinehttps://github.com/htmlwidgets/sparkline

但我不知道如何使用sparkcharts在markdown / html data.frame中创建。

我知道上面的链接中有一个示例,但我不知道如何自动在html中创建该数据框。

1 个答案:

答案 0 :(得分:1)

我认为这正是您所寻找的:https://leonawicz.github.io/HtmlWidgetExamples/ex_dt_sparkline.html

你也可以在这里找到一个虚拟的例子: R combining data tables DT package and sparkline package box plot with target value

举个例子: 按如下方式简化虚拟示例(忽略数据/表中的最后一列)

            library(data.table)
            library(DT)
            library(sparkline)



            hist.A<-rnorm(100)
            hist.B<-rnorm(100)
            hist.C<-rnorm(100)

            current.A<-rnorm(1)
            current.B<-rnorm(1)
            current.C<-rnorm(1)

            #whisker should show full range of data
            boxval.A<-paste(quantile(hist.A,probs=c(0,0.25,0.5,0.75,1)),collapse = ",")
            boxval.B<-paste(quantile(hist.B,probs=c(0,0.25,0.5,0.75,1)),collapse = ",")
            boxval.C<-paste(quantile(hist.C,probs=c(0,0.25,0.5,0.75,1)),collapse = ",")

            data<-data.frame(Variable=c("A","B","C"),Current=c(current.A,current.B,current.C),boxplot=c(boxval.A,boxval.B,boxval.C))
            data$boxWithTarget<-paste(data$boxplot,data$Current,Sep=",")

            cd <- list(list(targets = 2, render = JS("function(data, type, full){ return '<span class=sparkSamples>' + data + '</span>' }")))
            line_string <- "type: 'line', lineColor: 'black', fillColor: '#ccc', highlightLineColor: 'orange', highlightSpotColor: 'orange'"
            box_string <- "type: 'box', raw:true, showOutliers:false,lineColor: 'black', whiskerColor: 'black', outlierFillColor: 'black', outlierLineColor: 'black', medianColor: 'black', boxFillColor: 'orange', boxLineColor: 'black'"
            cb = JS("function (oSettings, json) {\n  $('.sparkSeries:not(:has(canvas))').sparkline('html', { ", 
                    line_string, " });\n  $('.sparkSamples:not(:has(canvas))').sparkline('html', { ", 
                    box_string, " });\n}")


            d <- datatable(data.table(data), rownames = FALSE, options = list(columnDefs = cd, 
                                                                                 fnDrawCallback = cb))
            d$dependencies <- append(d$dependencies, htmlwidgets:::getDependency("sparkline"))
            d