You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用visNetwork重现层级树并设置节点层级位置?

解决visNetwork层级树节点位置设置问题

尝试使用visNetwork包重现层级树,但无法为节点设置层级位置。以下是我的实现代码:

# Install and load the visNetwork package
install.packages("visNetwork")
library(visNetwork)
# Create nodes data frame
nodes <- data.frame(
  id = 1:7,
  label = c("BLADDER", "TRODELVY", "EV", "NO ADC RECEIVED", "EV", "NO ADC RECEIVED", "TRODELVY "),
  color = c("gray", "red", "blue", "gray", "blue", "gray", "red"),
  shape = "box"
)

# Create edges data frame
edges <- data.frame(
  from = c(1, 1, 2, 2, 3, 3),
  to = c(2, 3, 4, 5, 6, 7)
)

# Create the network visualization
visNetwork(nodes, edges) %>%
  visNodes(shape = "box") %>%
  visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)%>%
  visPhysics(solver = "hierarchicalRepulsion", 
             forceAtlas2Based = list(gravitationalConstant = -500))

层级树示例图


要实现规整的层级树布局,你不需要依赖物理引擎的hierarchicalRepulsion,直接用visNetwork内置的visHierarchicalLayout()函数就能精准控制节点层级:

修改后的代码:

# Install and load the visNetwork package
install.packages("visNetwork")
library(visNetwork)
# Create nodes data frame
nodes <- data.frame(
  id = 1:7,
  label = c("BLADDER", "TRODELVY", "EV", "NO ADC RECEIVED", "EV", "NO ADC RECEIVED", "TRODELVY "),
  color = c("gray", "red", "blue", "gray", "blue", "gray", "red"),
  shape = "box"
)

# Create edges data frame
edges <- data.frame(
  from = c(1, 1, 2, 2, 3, 3),
  to = c(2, 3, 4, 5, 6, 7)
)

# 生成带层级布局的网络图
visNetwork(nodes, edges) %>%
  visNodes(shape = "box") %>%
  visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE) %>%
  visHierarchicalLayout(
    direction = "UD",  # 层级方向:从上到下(可选LR=从左到右)
    sortMethod = "directed",  # 按边的指向自动识别层级
    levelSeparation = 200  # 层级间的间距
  ) %>%
  visPhysics(enabled = FALSE)  # 关闭物理引擎,固定节点位置

关键说明:

  • visHierarchicalLayout()是专门为层级树设计的布局函数,能根据边的父子关系自动排列节点;
  • 设置sortMethod = "directed"可以确保节点严格按照from->to的关系分布在对应层级;
  • 关闭物理引擎避免节点位置被动态调整,保证布局稳定;
  • 通过levelSeparation可以调整层级间距,让整体布局更清晰。

内容的提问来源于stack exchange,提问作者firmo23

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 18:21:10