我有一些分层数据,例如

> 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

我想通过一个圆形包装图以“自上而下”的 View 来绘制树:
http://bl.ocks.org/mbostock/4063530

r - 在ggplot2中用圆包装可视化分层数据?-LMLPHP

上面的链接是针对d3库的。有什么等效的方法可以让我在ggplot2中进行绘制吗?

(我想在一个支持d3的 Shiny 应用程序中使用此绘图,但是我以前从未使用过d3,并且不确定学习曲线。如果d3是显而易见的选择,我将尝试使其正常工作。谢谢。)

最佳答案

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

由于聚合的数据应具有与树图类似的结构,因此我们可以使用treemap包进行聚合(也可以使用具有连续聚合的循环)。然后,使用d3treeR(来自github)将树图数据转换为嵌套列表,并使用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,您应该看到
r - 在ggplot2中用圆包装可视化分层数据?-LMLPHP

要创建 Shiny 的绑定(bind),应该可以使用htmlwidgets并遵循一些示例(d3treeR源代码中有一些示例)来实现。请注意,某些功能不起作用,例如着色。存储在此处的json实际上包含许多有关节点的信息(所有数据都使用treemap聚合),您可以在图中利用这些信息。

关于r - 在ggplot2中用圆包装可视化分层数据?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33644266/

10-12 17:44
查看更多