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

R语言Plotly桑基图:添加链接数值与自定义悬浮提示

解决Plotly桑基图的两个自定义需求

下面是修改后的完整代码,可同时实现连接线上显示value数值和简化悬浮提示内容的功能:

library(plotly)
library(dplyr)

links <- data.frame(
  source=c("group_A","group_A", "group_B", "group_C", "group_C", "group_E"), 
  target=c("group_C","group_D", "group_E", "group_F", "group_G", "group_H"), 
  value=c(2,3, 2, 3, 1, 3)
)

nodes <- data.frame(
  name=c(as.character(links$source), 
         as.character(links$target)) %>% unique()
)

links$IDsource <- match(links$source, nodes$name)-1 
links$IDtarget <- match(links$target, nodes$name)-1

plot_ly(
  type = "sankey",
  orientation = "h",
  textfont = list(size=11),
  node = list(
    label = nodes$name,
    pad = 15,
    thickness = 20),
  link = list(
    source = links$IDsource,
    target = links$IDtarget,
    value = links$value,
    # 实现需求1:在连接线上显示value数值
    text = links$value,
    showtext = TRUE,
    textfont = list(size=10), # 可按需调整数值字体大小
    # 实现需求2:自定义悬浮提示内容
    hovertemplate = "value : %{value}<extra></extra>"
  )
)

关键修改说明:

  • 需求1:连线显示数值
    在link参数组中添加:

    • text = links$value:指定每条连线的显示文本为对应的value值
    • showtext = TRUE:开启连线文本显示开关
    • 可选textfont:自定义数值的字体大小、颜色等样式
  • 需求2:简化悬浮提示
    在link参数组中设置hovertemplate = "value : %{value}<extra></extra>":

    • %{value}会自动映射为对应连线的数值
    • <extra></extra>用于清除默认的source/target冗余信息,仅保留自定义内容

若运行时出现参数失效问题,建议先更新plotly包:install.packages("plotly")

内容的提问来源于stack exchange,提问作者Chloé

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 22:52:12