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

R语言Plotly绘制桑基图设置链路与源节点同色及悬停加深方法

解决方案

两个需求可通过新增节点配色映射、链路颜色继承、悬停样式配置三步实现,修改后的完整代码如下:

library(data.table)
library(plotly)
library(RColorBrewer)

dt <- setDT(copy(dt_minors2016))
nodes <- dt[,unique(c(citizen,geo))]
sources <- match(dt[,citizen],nodes)-1
targets <- match(dt[,geo], nodes) -1
values <- dt[,V1]

# 定义节点颜色,可替换为自定义颜色向量,长度需和节点数量保持一致
node_colors <- brewer.pal(length(nodes), "Set2")
# 生成与源节点同色的半透明链路颜色(默认透明度0.4)
link_colors <- sapply(sources, function(idx) {
  rgb_val <- col2rgb(node_colors[idx + 1])
  sprintf("rgba(%s,%s,%s,0.4)", rgb_val[1], rgb_val[2], rgb_val[3])
})
# 生成悬停时加深的链路颜色(透明度调整为0.8实现加深效果)
link_hover_colors <- sapply(sources, function(idx) {
  rgb_val <- col2rgb(node_colors[idx + 1])
  sprintf("rgba(%s,%s,%s,0.8)", rgb_val[1], rgb_val[2], rgb_val[3])
})

fig <- plot_ly(
  type = "sankey",
  domain = list(
    x =  c(0,1),
    y =  c(0,1)
  ),
  orientation = "h",
  valueformat = ".0f",
  valuesuffix = "Persons",
  
  node = list(
    label = nodes,
    color = node_colors, # 替换为预定义的节点颜色
    pad = 15,
    thickness = 15,
    line = list(
      color = "black",
      width = 0.5
    )
  ),
  
  link = list(
    source = sources,
    target = targets,
    value =  values,
    color = link_colors, # 替换为继承源节点的链路颜色
    hovercolor = link_hover_colors # 配置悬停加深颜色
  )
)
fig <- fig %>% layout(
  title = "UAM asylum seekers from top 5 origin countries to EU countries - 2016",
  font = list(
    size = 10
  ),
  xaxis = list(showgrid = F, zeroline = F),
  yaxis = list(showgrid = F, zeroline = F),
  hovermode = "x unified"
)

fig

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:06:03