如何在R中并排展示两个data.tree包生成的树结构图形
实现方案
你生成的树图本质是DiagrammeR输出的htmlwidget对象,无法兼容R基础绘图、ggplot生态的布局逻辑,可采用以下两种方案实现并排:
方案1:htmltools流式布局(交互式场景优先)
该方案无需修改你原有生成树的代码逻辑,适合在RStudio Viewer、R Markdown、Shiny中使用:
# 加载布局依赖包 library(htmltools) # 原有生成树逻辑保持不变 library(data.tree) library(DiagrammeR) acme <- Node$new("Acme Inc.") accounting <- acme$AddChild("Accounting") software <- accounting$AddChild("New Software") standards <- accounting$AddChild("New Accounting Standards") acme2 <- Node$new("Acme Inc. 2") accounting2 <- acme2$AddChild("Accounting 2") software2 <- accounting2$AddChild("New Software 2") standards2 <- accounting2$AddChild("New Accounting Standards 2") # 两列并排布局,每列占50%宽度 browsable( fluidRow( column(width = 6, plot(acme)), column(width = 6, plot(acme2)) ) )
方案2:合并DOT语法生成单图(静态导出场景优先)
如果需要导出为png、pdf等静态格式,可以提取每个树的DOT定义,合并为单个带子图的DOT文件渲染:
# 分别提取两个树的DOT原始代码 dot1 <- ToGraphViz(acme)$dot_code dot2 <- ToGraphViz(acme2)$dot_code # 提取两个图的核心节点、边配置,去除外层digraph包裹 sub_graph1 <- gsub("^digraph \\w+ \\{|\\}$", "", dot1) sub_graph2 <- gsub("^digraph \\w+ \\{|\\}$", "", dot2) # 合并为单个digraph,设置左右排布规则 merged_dot <- sprintf(" digraph merged_tree { rankdir=LR; subgraph cluster_1 { label = \"方案树1\"; %s } subgraph cluster_2 { label = \"方案树2\"; %s } } ", sub_graph1, sub_graph2) # 渲染合并后的单图 grViz(merged_dot)
渲染后的单图可直接通过export_graph()函数导出为任意静态格式,完全适配你通过循环生成树的现有逻辑。
内容的提问来源于stack exchange,提问作者User2321
相关产品推荐
相关产品推荐

