You need to enable JavaScript to run this app. R中使用networkD3绘制桑基图时通过LinkGroup实现产品图例展示的问题
优惠活动
大模型
产品
解决方案
定价
更多

R中使用networkD3绘制桑基图时通过LinkGroup实现产品图例展示的问题

networkD3 包的 sankeyNetwork() 函数本身没有内置基于 LinkGroup 字段自动生成图例的功能,你可以通过 htmltools 自定义图例并和桑基图拼接实现需求,以下是修改后可直接运行的完整代码:

library(htmltools)
library(htmlwidgets)
library(magrittr)
library(networkD3)
library(tidyr)
library(RColorBrewer)
library(jsonlite)

# 原始数据
Sankey <- data.frame(
  "origin" = c('country A', 'country A', 'country A', 'country A', 'country B', 'country B', 'country C', 'country C'),
  "destination" = c('country B', 'country B', 'country C', 'country D', 'country D', 'country D', 'country E', 'country E'),
  'product' = c('Meat', 'Palm oil', 'Meat', 'Meat', 'Wheat', 'Other', 'Rice', 'Nuts'),
  'number' = c(10, 10, 20, 30, 40, 35, 50,10)
) 

# 节点处理
nodes <- as.data.frame(union(unique(Sankey$origin), unique(Sankey$destination))) %>%
  rename(Countries = 1)

Sankey$ID_major_Origin_EU <- match(Sankey$origin, nodes$Countries)-1 
Sankey$ID_major_Destination_EU <- match(Sankey$destination, nodes$Countries)-1

nodes %<>% tidyr::separate(Countries, "Countries", sep = "_")

# 提取产品分类和对应配色
product_list <- unique(Sankey$product)
product_colors <- brewer.pal(length(product_list), "Set2")

# 构建图例
legend <- tags$div(
  style = "display: flex; flex-direction: column; gap: 8px; padding: 20px; font-size: 16px;",
  tags$h3("产品类别"),
  lapply(1:length(product_list), function(i) {
    tags$div(
      style = "display: flex; align-items: center; gap: 8px;",
      tags$span(style = paste0("display: inline-block; width: 20px; height: 20px; background-color: ", product_colors[i], ";")),
      tags$span(product_list[i])
    )
  })
)

# 构建桑基图+图例的完整页面
tagList(
  tags$h1("2013 - embodied HANPP"),
  tags$div(
    style = "display: flex; align-items: center;",
    sankeyNetwork(
      Links = Sankey, 
      Nodes = nodes, 
      Source = "ID_major_Origin_EU", Target = "ID_major_Destination_EU", 
      Value = "number", NodeID = "Countries",
      units = "t dm", fontSize = 20, nodeWidth = 30,
      height = 600,
      LinkGroup = "product",
      colourScale = JS(paste0("d3.scaleOrdinal().domain(", toJSON(product_list), ").range(", toJSON(product_colors), ")"))
    ),
    legend
  )
)

运行上述代码后,就会在桑基图的右侧自动生成和链路配色完全对应的产品分类图例。如果需要调整样式,直接修改对应style属性的参数即可:

  • 修改padding调整图例边距
  • 修改gap调整图例条目间距
  • 修改颜色向量product_colors自定义配色
  • 调整flex布局参数可以修改图例的摆放位置

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 02:57:02