在 ggplot2 中使用圆形包装可视化分层数据?

Visualizing hierarchical data with circle packing in ggplot2?

我有一些分层数据,例如,

> library(dplyr)
> df <- data_frame(id = 1:6, parent_id = c(NA, 1, 1, 2, 2, 5))
> df
Source: local data frame [6 x 2]

     id parent_id
  (int)     (dbl)
1     1        NA
2     2         1
3     3         1
4     4         2
5     5         2
6     6         5

我想通过圆形填充图在 "top down" 视图中绘制树: http://bl.ocks.org/mbostock/4063530

上面的 link 是针对 d3 库的。是否有一个等价物允许我在 ggplot2 中绘制这样的图?

(我想在一个支持 d3 的闪亮应用程序中使用此图,但我之前没有使用过 d3,并且不确定学习曲线。如果 d3 是显而易见的选择,我会尝试让它工作相反。谢谢。)

有两个步骤:(1) 汇总数据,然后 (2) 转换为 json。之后,所有 javascript 都已写入该示例页面,因此您只需插入生成的 json 数据即可。

由于聚合数据应该具有类似于树图的结构,我们可以使用 treemap 包来进行聚合(也可以使用具有连续聚合的循环)。然后,d3treeR(来自github)用于将树图数据转换为嵌套列表,并使用jsonlite将列表转换为json。

我正在使用在 d3treeR 包中找到的一些示例数据 GNI2010。您可以在 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 聚合的所有数据),您可以在图中利用这些信息。