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

如何在Plotly子图中为每个子图单独添加图例?

Plotly R 子图实现独立图例的解决方案

在Plotly的subplot中,默认会将同名的trace图例合并,这就是你遇到所有图例集中在右上角的原因。要实现每个子图对应独立图例,需要做两个关键调整:

  1. 给每个子图的trace设置唯一名称,避免Plotly自动合并图例
  2. 为每个子图单独设置图例的显示位置,确保图例依附在对应子图旁

修改后的代码如下:

library(plotly)

# 子图1:设置唯一name,单独配置图例位置
fig1 <- plot_ly(
  x = c("giraffes", "orangutans", "monkeys"),
  y = c(20, 14, 23),
  name = "SF Zoo 1",  # 唯一名称
  type = "bar",
  marker = list(color = '#ff7f0e')
) %>% 
  layout(
    legend = list(x = 1, y = 1, xanchor = "right", yanchor = "top"),  # 子图右上角
    showlegend = TRUE
  )

# 子图2:同理设置唯一name和图例位置
fig2 <- plot_ly(
  x = c("giraffes", "orangutans", "monkeys"),
  y = c(50, 24, 3),
  name = "SF Zoo 2",
  type = "bar",
  marker = list(color = '#d62728')
) %>% 
  layout(
    legend = list(x = 1, y = 1, xanchor = "right", yanchor = "top"),
    showlegend = TRUE
  )

# 子图3
fig3 <- plot_ly(
  x = c("giraffes", "orangutans", "monkeys"),
  y = c(10, 24, 67),
  name = "SF Zoo 3",
  type = "bar",
  marker = list(color = '#9370DB')
) %>% 
  layout(
    legend = list(x = 1, y = 1, xanchor = "right", yanchor = "top"),
    showlegend = TRUE
  )

# 子图4
fig4 <- plot_ly(
  x = c("giraffes", "orangutans", "monkeys"),
  y = c(10, 24, 67),
  name = "SF Zoo 4",
  type = "bar",
  marker = list(color = '#2ca02c')
) %>% 
  layout(
    legend = list(x = 1, y = 1, xanchor = "right", yanchor = "top"),
    showlegend = TRUE
  )

# 合并子图,注意不需要额外用style设置showlegend
fig <- subplot(
  fig1, fig2, fig3, fig4,
  nrows = 2, 
  margin = 0.05,
  shareX = TRUE,  # 可选,根据需求设置是否共享X轴
  shareY = TRUE
)

fig

关键说明:

  • 唯一名称:每个trace的name必须不同,否则Plotly会自动合并相同名称的图例,无法实现独立显示
  • 图例位置:通过layout(legend = ...)给每个子图单独设置图例位置,x=1,y=1表示子图的右上角,xanchor和yanchor用来对齐图例的锚点,确保图例不会超出子图范围
  • subplot参数:如果不需要共享坐标轴,可以去掉shareX和shareY,根据你的可视化需求调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 22:12:51