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

Plotly折线图图例能否置于折线末端而非图例框中?

在Plotly中实现折线末端标注(替代末端图例)

Plotly本身没有直接将图例放在折线末端的原生功能,但可以通过两种可靠的方式实现,同时避免重叠问题:

方法1:利用annotations精准定位

通过获取每条折线的最后一个数据点坐标,动态生成标注,设置位置偏移避免重叠:

import plotly.graph_objects as go
import numpy as np

# 示例数据
x = np.linspace(0, 10, 20)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x[:15])  # 避免无穷值

fig = go.Figure()
# 添加折线
fig.add_trace(go.Scatter(x=x, y=y1, name='正弦曲线', mode='lines'))
fig.add_trace(go.Scatter(x=x, y=y2, name='余弦曲线', mode='lines'))
fig.add_trace(go.Scatter(x=x[:15], y=y3, name='正切曲线', mode='lines'))

# 为每条折线添加末端标注
for trace in fig.data:
    # 获取最后一个点的坐标
    last_x = trace.x[-1]
    last_y = trace.y[-1]
    # 添加标注,设置x轴偏移避免重叠,根据trace索引调整
    fig.add_annotation(
        x=last_x,
        y=last_y,
        text=trace.name,
        showarrow=False,
        xshift=10 + (trace.index * 30),  # 不同折线偏移量递增,防止重叠
        yshift=0,
        font=dict(size=10)
    )

# 隐藏原生图例
fig.update_layout(showlegend=False)
fig.show()

方法2:用散点标记+文本模式

直接在折线末端添加带文本的散点,替代标注,更简洁:

import plotly.graph_objects as go
import numpy as np

x = np.linspace(0, 10, 20)
y1 = np.sin(x)
y2 = np.cos(x)

fig = go.Figure()
# 添加折线(无标记)
fig.add_trace(go.Scatter(x=x, y=y1, name='正弦曲线', mode='lines'))
fig.add_trace(go.Scatter(x=x, y=y2, name='余弦曲线', mode='lines'))

# 添加末端带文本的散点
fig.add_trace(go.Scatter(
    x=[x[-1]], y=[y1[-1]],
    text=['正弦曲线'],
    mode='text',
    showlegend=False,
    textposition='middle right'
))
fig.add_trace(go.Scatter(
    x=[x[-1]], y=[y2[-1]],
    text=['余弦曲线'],
    mode='text',
    showlegend=False,
    textposition='middle right',
    textfont=dict(color='#636EFA')  # 和对应折线颜色一致
))

fig.update_layout(showlegend=False)
fig.show()

避免重叠的关键技巧

  • 动态设置xshift/yshift:根据折线数量或索引,给每个标注设置不同的偏移量
  • 调整textposition:可选top right/bottom right等不同位置,错开不同折线的文本
  • 限制文本长度:过长的名称可以缩写,或者调整字体大小

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:01:04