有两个步骤:(1)聚合数据,然后(2)转换为 json。在那之后,所有的 javascript 都写在那个示例页面中,所以你可以插入生成的 json 数据。
由于聚合数据应该具有类似于树形图的结构,我们可以使用treemap 包进行聚合(也可以使用循环连续聚合)。然后,d3treeR(来自github)用于将treemap数据转换为嵌套列表,jsonlite将列表转换为json。
我正在使用GNI2010 包中的一些示例数据d3treeR。您可以在plunker 上查看所有源文件。
library(treemap)
library(d3treeR) # devtools::install_github("timelyportfolio/d3treeR")
library(data.tree)
library(jsonlite)
## Get treemap data using package treemap
## Using example data GNI2010 from d3treeR package
data(GNI2010)
## aggregate by these: continent, iso3,
## size by population, and color by GNI
indexList <- c('continent', 'iso3')
treedat <- treemap(GNI2010, index=indexList, vSize='population', vColor='GNI',
type="value", fun.aggregate = "sum",
palette = 'RdYlBu')
treedat <- treedat$tm # pull out the data
## Use d3treeR to convert to nested list structure
## Call the root node 'flare' so we can just plug it into the example
res <- d3treeR:::convert_treemap(treedat, rootname="flare")
## Convert to JSON using jsonlite::toJSON
json <- toJSON(res, auto_unbox = TRUE)
## Save the json to a directory with the example index.html
writeLines(json, "d3circle/flare.json")
我还将示例中的源代码行 index.html 替换为
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
然后启动 index.html,你应该会看到
使用htmlwidgets 并遵循一些示例(d3treeR 源有一些)应该可以创建闪亮的绑定。请注意,某些事情不起作用,例如着色。此处存储的 json 实际上包含很多关于节点的信息(使用treemap 聚合的所有数据),您可以在图中利用这些信息。