我有一些分层数据,例如,
> 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
上面的链接适用于 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 你应该看到
使用
htmlwidgets
创建 Shiny 的绑定(bind)应该是可行的。并遵循一些示例(d3treeR
来源有一些)。请注意,某些事情不起作用,例如着色。存储在这里的 json 实际上包含很多关于节点的信息(所有使用 treemap
聚合的数据),您可以在图中利用这些信息。
关于r - 在ggplot2中使用圆形包装可视化分层数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33644266/