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

R语言Plotly桑基图添加左右外侧垂直标签的实现问题咨询

问题原因

标注消失是两个默认设置导致的:

  1. 绘图区左右边距过小,没有预留显示外部标注的空间
  2. 标注默认开启了坐标轴裁剪,超出绘图区范围的内容会被自动隐藏

解决方案

你只需要在原有代码基础上调整边距、关闭标注裁剪,即可实现左右两侧垂直标签的添加,完整可运行代码如下:

library(plotly)
fig <- plot_ly(
  type = "sankey",
  orientation = "h",
  
  node = list(
    label = c("Level 1", "Level 2", "Level 3",
              "Level 1", "Level 2", "Level 3", "Level 4", "Level 5"),
    color = c("rgba(34,139,34, 1)", "rgba(31, 119, 180, 1)", "rgba(255, 127, 14, 1)",
              "rgba(34,139,34, 1)", "rgba(31, 119, 180, 1)", "rgba(255, 127, 14, 1)", "rgba(148, 103, 189, 1)", "rgba(148, 103, 0, 1)"),
    pad = 20,
    thickness = 15,
    line = list(
      color = "black",
      width = 0.5
    )
  ),
  
  link = list(
    source = c(0,0,0,0,1,1,1,1,2,2,2,2),
    target = c(3,4,5,6,3,4,5,6,4,5,6,7),
    value =  c(482,52,1,1,20,127,19,1,1,1,3,1),
    color = c("rgba(34,139,34,0.4)", "rgba(34,139,34,0.4)", "rgba(34,139,34,0.4)", "rgba(34,139,34,0.4)",
              "rgba(31, 119, 180, 0.4)", "rgba(31, 119, 180, 0.4)", "rgba(31, 119, 180, 0.4)", "rgba(31, 119, 180, 0.4)",
              "rgba(255, 127, 14, 0.4)", "rgba(255, 127, 14, 0.4)", "rgba(255, 127, 14, 0.4)", "rgba(255, 127, 14, 0.4)")
  )
)
fig <- fig %>% layout(
  title = "Title of the Plot",
  font = list(
    size = 10
  ),
  # 关键修改1:设置左右边距,预留标签显示空间
  margin = list(l = 120, r = 120, t = 50, b = 50)
) %>% 
# 添加左侧垂直标签
add_annotations(
  xref="paper",
  yref="paper",
  x=-0.15,
  y=0.5,
  text="左侧标签",
  showarrow=FALSE,
  # 关键修改2:关闭坐标轴裁剪
  cliponaxis = FALSE,
  # 关键修改3:设置文字垂直显示
  textangle = -90,
  font = list(size = 14)
) %>%
# 添加右侧垂直标签
add_annotations(
  xref="paper",
  yref="paper",
  x=1.15,
  y=0.5,
  text="右侧标签",
  showarrow=FALSE,
  cliponaxis = FALSE,
  textangle = 90,
  font = list(size = 14)
)

fig

参数调整说明

  • 标签位置不合适可以调整x的数值:左侧标签x越小越靠左,右侧标签x越大越靠右
  • margin的l、r数值可以根据标签长度调整,避免标签被截断
  • textangle可以根据文字阅读方向调整:-90是从上到下读,90是从下到上读

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 03:15:01