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

如何在Shiny应用中让visNetwork全屏放大并完整显示?

让Shiny中visNetwork网络图全屏显示并清晰展示节点的方法

要解决网络图无法全屏显示、节点辨识度低的问题,可以从容器尺寸、网络参数、布局优化三个维度调整:


1. 调整Shiny UI的输出容器尺寸

将visNetworkOutput的宽高设置为占满整个浏览器视口,同时移除页面默认边距,避免留白:

ui <- fluidPage(
  tags$style("body {margin: 0; padding: 0;}"),
  visNetworkOutput("net", width = "100%", height = "100vh")
)
  • 100vh是视口高度单位,确保容器撑满浏览器窗口高度;100%让宽度匹配窗口宽度。

2. 匹配visNetwork函数的宽高设置

在生成网络图时,将宽高设为"100%",让网络图完全填满父容器:

visNetwork(nodes, edges, width = "100%", height = "100%") %>%

3. 优化节点与布局参数提升清晰度

  • 调整节点尺寸与字体:避免过大/过小的节点尺寸,同时设置合适的字体大小保证文字可读;
  • 优化层级布局:调整levelSeparation和nodeSpacing,避免节点拥挤重叠;
  • 开启交互功能:添加缩放、拖拽功能,方便用户手动调整视角。

修改后的完整代码

library(shiny)
library(dplyr)
library(visNetwork)

# Define UI
ui <- fluidPage(
  # 移除页面默认边距,让网络完全占满窗口
  tags$style("body {margin: 0; padding: 0;}"),
  visNetworkOutput("net", width = "100%", height = "100vh")
)

# Define server logic
server <- function(input, output, session) {
  output$net<-renderVisNetwork({
    # Original 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",
      level = c(1, 2, 2, 3, 3, 3, 3)
    )
    
    # Generate new nodes
    new_node_ids <- 8:27
    new_node_labels <- paste("NODE", new_node_ids)
    new_nodes <- data.frame(
      id = new_node_ids,
      label = new_node_labels,
      color = "yellow",
      shape = "box",
      level = 4
    )
    
    # Combine the nodes data frames
    nodes <- rbind(nodes, new_nodes)
    
    # Original edges data frame
    edges <- data.frame(
      from = c(1, 1, 2, 2, 3, 3),
      to = c(2, 3, 4, 5, 6, 7)
    )
    
    # Add new edges
    new_edges <- data.frame(
      from = rep(4:7, each = 5),
      to = new_node_ids
    )
    
    # Combine the edges data frames
    edges <- rbind(edges, new_edges)
    
    # Create the network visualization
    visNetwork(nodes, edges, width = "100%", height = "100%") %>%
      visNodes(shape = "square", size = 60, font = list(color = "white", size = 14)) %>% # 调整节点尺寸和字体大小
      visOptions(highlightNearest = TRUE, nodesIdSelection = FALSE) %>%
      visHierarchicalLayout(levelSeparation = 250, nodeSpacing = 150, direction = "LR") %>% # 优化布局间距
      visInteraction(zoom = TRUE, dragView = TRUE) # 开启缩放和拖拽功能
  })
}

# Run the application 
shinyApp(ui = ui, server = server)

内容的提问来源于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 09:00:05