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

如何将networkD3绘制的Sankey图显示在R的Plots面板而非Viewer面板?

解决networkD3桑基图无法导出PDF的问题

networkD3生成的桑基图是交互式HTML可视化,默认只会在RStudio的Viewer面板展示,而Plots面板仅支持静态图形(如ggplot2、基础绘图),所以无法直接在Plots面板导出PDF。可以通过以下两种方法实现导出需求:

方法一:用webshot2将HTML转为图片再导出PDF

此方法先把桑基图保存为HTML,再转为静态图片,最后将图片导出为PDF。

# 安装依赖包
install.packages(c("networkD3", "webshot2", "ggplot2", "png"))
library(networkD3)
library(webshot2)
library(ggplot2)
library(png)

# 生成桑基图(保留原代码逻辑)
concept <- c("Vulnerability", "Adaptation", "Resilience")
nodes <- data.frame(concept)
source <- c(0, 1, 0)
target <- c(1, 2, 2)
value <- c(76, 48, 42)
links <- data.frame(source, target, value)

my_color <- 'd3.scaleOrdinal() .domain(["Vulnerability", "Adaptation","Resilience"]) .range(["brown", "green" , "blue"])'

sankey_plot <- sankeyNetwork(Links = links, Nodes = nodes, Source = "source",
                             Target = "target", Value = "value", NodeID = "concept", colourScale=my_color, 
                             units = "Indicators", fontSize = 12, 
                             nodeWidth = 30)

# 1. 保存桑基图为独立HTML文件
saveNetwork(sankey_plot, "sankey_plot.html", selfcontained = TRUE)

# 2. 将HTML转为PNG静态图片(可调整vwidth/vheight控制尺寸)
webshot("sankey_plot.html", "sankey_plot.png", vwidth = 800, vheight = 600)

# 3. 将图片导入并导出为PDF
img <- readPNG("sankey_plot.png")
pdf_plot <- ggplot() + 
  annotation_raster(img, xmin = -Inf, xmax = Inf, ymin = -Inf, ymax = Inf) +
  theme_void()

ggsave("sankey_plot.pdf", pdf_plot, width = 8, height = 6)

方法二:用R Markdown直接编译为PDF

通过R Markdown文档编译,knitr会自动将交互式桑基图转为静态图片嵌入PDF中:

  1. 新建一个.Rmd文件,填入以下内容:
---
title: "桑基图PDF导出"
output: pdf_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE)
library(networkD3)
# 桑基图代码
concept <- c("Vulnerability", "Adaptation", "Resilience")
nodes <- data.frame(concept)
source <- c(0, 1, 0)
target <- c(1, 2, 2)
value <- c(76, 48, 42)
links <- data.frame(source, target, value)

my_color <- 'd3.scaleOrdinal() .domain(["Vulnerability", "Adaptation","Resilience"]) .range(["brown", "green" , "blue"])'

sankeyNetwork(Links = links, Nodes = nodes, Source = "source",
              Target = "target", Value = "value", NodeID = "concept", colourScale=my_color, 
              units = "Indicators", fontSize = 12, 
              nodeWidth = 30)
2. 点击RStudio中的"Knit"按钮,选择编译为PDF即可。

内容的提问来源于stack exchange,提问作者Nabila Hasan
相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 20:01:13