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

如何将Plotly图表的图例放置在图表顶部而非底部?

如何将Plotly图表图例从底部移至顶部(R语言)

你只需要在layout()的legend参数中添加位置控制参数,就能把水平排列的图例从底部移到顶部。修改后的完整代码如下:

library(plotly)
library(tidyr)
library(plyr)

data <- spread(Orange, Tree, circumference)
data <- rename(data, c("1" = "Tree1", "2" = "Tree2", "3" = "Tree3", "4" = "Tree4", "5" = "Tree5"))

fig <- plot_ly(data, x = ~age, y = ~Tree1, type = 'scatter', mode = 'lines', name = 'Tree 1')
fig <- fig %>% add_trace(y = ~Tree2, name = 'Tree 2')
fig <- fig %>% add_trace(y = ~Tree3, name = 'Tree 3')
fig <- fig %>% add_trace(y = ~Tree4, name = 'Tree 4')
fig <- fig %>% add_trace(y = ~Tree5, name = 'Tree 5')
# 修改legend参数,添加位置控制
fig <- fig %>% layout(legend = list(
  orientation = 'h',  # 保持水平排列
  y = 1,              # 定位到图表顶部
  yanchor = 'top',    # 图例顶部对齐图表顶部
  x = 0.5,            # 水平方向居中(可选)
  xanchor = 'center'  # 图例中心对齐x=0.5的位置(可选)
))

fig

关键参数说明:

  • orientation = 'h':维持图例的水平排列方式,和你原代码一致
  • y = 1:Plotly的坐标系统中,y轴范围是0(底部)到1(顶部),设置为1表示把图例放在顶部区域
  • yanchor = 'top':确保图例自身的顶部边缘和图表顶部对齐,避免图例部分超出图表范围
  • x = 0.5和xanchor = 'center':让图例在水平方向居中显示,如果你需要左对齐或右对齐,可以调整x和xanchor的值(比如x=0对应左对齐,xanchor='left')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 03:22:38