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

如何为Plotly 5.9图例设置与轨迹不同的属性?

Plotly 散点图:单独设置图例标记的透明度与尺寸

解决方案

想做到只改图例标记的透明度和尺寸,同时让绘图区的低透明度数据点保持不变,可以用下面两种方法配合实现:

1. 统一图例标记尺寸

用itemsizing='constant'让所有图例标记采用固定尺寸(不再跟随轨迹本身的marker大小):

fig.update_layout(legend={'itemsizing': 'constant'})

2. 单独设置图例标记的透明度(及自定义尺寸)

Plotly 5.9可以通过layout.legend.entries单独配置每个图例条目的标记属性,包括透明度和尺寸。直接给每个轨迹对应的图例条目设置参数即可:

fig.update_layout(
    legend=dict(
        entries=[
            # 第一个轨迹的图例:完全不透明,标记尺寸10
            dict(traceindex=0, marker=dict(opacity=1, size=10)),
            # 第二个轨迹的图例:完全不透明,标记尺寸10
            dict(traceindex=1, marker=dict(opacity=1, size=10))
        ]
    )
)

完整代码示例

把上面的配置整合到你的代码中,最终代码如下:

import numpy as np
import plotly.graph_objs as go
from plotly.offline import plot
from plotly.subplots import make_subplots
from IPython.display import display, HTML

x = np.random.rand(2000)
y1 = np.random.rand(2000)
y2 = np.random.randn(2000)

fig = make_subplots(rows=1, cols=2)

trc1 = go.Scatter(x=x, y=y1, mode='markers', marker=dict(
    color='blue', size=2, opacity=0.2)
)
trc2 = go.Scatter(x=x, y=y2, mode='markers', marker=dict(
    color='green', size=4, opacity=0.2)
)

fig.add_trace(trc1, row=1, col=1)
fig.add_trace(trc2, row=1, col=2)

# 统一图例标记为固定尺寸
fig.update_layout(legend={'itemsizing': 'constant'})

# 单独设置图例标记的透明度和尺寸,不影响绘图区的点
fig.update_layout(
    legend=dict(
        entries=[
            dict(traceindex=0, marker=dict(opacity=1, size=10)),
            dict(traceindex=1, marker=dict(opacity=1, size=10))
        ]
    )
)

display(HTML(plot(fig, output_type="div")))

原理说明

  • itemsizing='constant':强制图例标记使用统一尺寸,避免跟随轨迹本身的小marker,让图例显示更清晰。
  • legend.entries:针对每个图例条目(通过traceindex指定对应轨迹)单独设置marker属性,这里将opacity设为1(完全不透明),同时自定义size为10,这些设置仅作用于图例,不会改变绘图区域的数据点样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 08:25:09