【问题标题】:Visualizing hierarchical data with circle packing in ggplot2?在ggplot2中使用圆形包装可视化分层数据?
【发布时间】:2016-02-12 04:09:24
【问题描述】:

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

> 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

我想通过圆形包装图在“自上而下”的视图中绘制树: http://bl.ocks.org/mbostock/4063530

以上链接适用于 d3 库。是否有等价物可以让我在 ggplot2 中制作这样的情节?

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

【问题讨论】:

    标签: r ggplot2 treemap


    【解决方案1】:

    有两个步骤:(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 聚合的所有数据),您可以在图中利用这些信息。

    【讨论】:

    • 漂亮,谢谢!我很惊讶你这么快就知道了。我已经将您的答案复制到(但不包括)htmlwidgets 点而没有问题。我遇到的唯一问题(以防它帮助其他人):(1)我必须先运行data(GNI2010)。 (2) 最初 index.html 加载的是一个空白页面,通过this stackoverflow answer 中描述的启动本地服务器来解决。
    • 太棒了!我本来希望更进一步并制作 htmlwidget,但我没有这方面的经验。虽然,看代码github.com/timelyportfolio/d3treeR/blob/master/R/d3tree.R#L122 看起来很可行。
    • 非常感谢您的回答。此外,您可能希望查看 data.tree github.com/gluc/data.tree 以了解聚合和树操作。我发现它非常有帮助。
    • 什么是对象“GNI2010”? R 没有找到它(在建议的解决方案中)
    • @user3245256 相信需要加载,看第一条评论
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 2013-11-14
    相关资源
    最近更新 更多