为何visNetwork生成的HTML图表布局尺寸过小?
I get it—your visNetwork chart is showing up way too small in Chrome and Firefox, even though you set width = "100%" and height = "100%". The problem here is how HTML handles percentage-based heights: your chart's parent container (the code block wrapper in the generated HTML) doesn't have an explicit height defined, so the browser can't figure out what "100%" actually translates to, and collapses the chart to a tiny size.
Here are two reliable fixes to get your chart looking the way you want:
Solution 1: Use a Fixed Pixel Height (Quick & Simple)
Replace the percentage height with a specific pixel value (like 600px) to directly control the chart's dimensions. This works great if you want a consistent size across all devices:
require(visNetwork, quietly = TRUE) nodes <- data.frame(id = 1:20) edges <- data.frame(from = sample(c(1:20), 10), to = sample(c(1:20), 10)) visNetwork(nodes, edges, width = "100%", height = "600px") %>% visNodes() %>% visOptions(highlightNearest = TRUE) %>% visInteraction(navigationButtons = TRUE, dragNodes = FALSE, dragView = FALSE, zoomView = FALSE) %>% visEdges(arrows = 'to')
Solution 2: Responsive Height with CSS (Adapts to Screen Size)
For a more flexible, responsive approach, add custom CSS to your R Markdown file. This sets a proper height for the container holding the visNetwork chart, letting your height = "100%" setting work as intended:
Add this right after your YAML header at the top of the Rmd file:
<style> /* Target the container that wraps the visNetwork plot */ div.visNetwork { height: 80vh !important; /* Uses 80% of the viewport height */ width: 100% !important; } </style>
With this CSS in place, you can keep using height = "100%" in your visNetwork() call—the chart will now fill 80% of the browser window's height, adjusting automatically if the user resizes their window.
Why Your Original Code Didn't Work
HTML elements use percentage heights relative to their parent element's height. Since the default code block container in R Markdown's HTML output doesn't have a defined height, the browser can't calculate what "100%" should be, so it shrinks the chart to the minimum size needed to display its content.
内容的提问来源于stack exchange,提问作者Christoph

