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

如何为Plotly图表的不同Y轴范围设置背景色?

实现Plotly折线图按Y轴均值分区域设置背景色

要给Plotly多折线图按Y轴均值划分上下区域,设置不同浅紫色背景,核心是通过shapes参数添加两个覆盖整个X轴范围的矩形,分别对应均值上下区间。以下是完整的实现示例:

示例代码

import plotly.graph_objects as go
import numpy as np

# 构造示例数据
x = np.arange(1, 11)
y1 = np.random.randint(10, 30, size=10)
y2 = np.random.randint(15, 35, size=10)
y3 = np.random.randint(5, 25, size=10)

# 计算所有Y数据的均值作为分界
all_y_data = np.concatenate([y1, y2, y3])
mean_y = np.mean(all_y_data)
# 获取Y轴的最小和最大值
min_y = np.min(all_y_data)
max_y = np.max(all_y_data)

# 创建图表
fig = go.Figure()

# 添加多条折线
fig.add_trace(go.Scatter(x=x, y=y1, name='Series 1'))
fig.add_trace(go.Scatter(x=x, y=y2, name='Series 2'))
fig.add_trace(go.Scatter(x=x, y=y3, name='Series 3'))

# 添加背景色区域
fig.update_layout(
    shapes=[
        # 均值以下区域:#eeeeee
        dict(
            type='rect',
            xref='paper',  # X轴使用图表比例(0=左,1=右)
            yref='y',      # Y轴使用实际数值
            x0=0,
            x1=1,
            y0=min_y,
            y1=mean_y,
            fillcolor='#eeeeee',
            opacity=0.5,
            layer='below',  # 把背景放在折线下方
            line_width=0,   # 去掉边框
        ),
        # 均值以上区域:#f5f5f5
        dict(
            type='rect',
            xref='paper',
            yref='y',
            x0=0,
            x1=1,
            y0=mean_y,
            y1=max_y,
            fillcolor='#f5f5f5',
            opacity=0.5,
            layer='below',
            line_width=0,
        )
    ],
    yaxis_title='Value',
    xaxis_title='X',
    title='Multi-line Chart with Mean-based Background'
)

fig.show()

关键说明

  • 均值计算:合并所有折线的Y数据计算均值,确保分界是全局的;如果需要单条折线的均值,只需针对对应系列计算即可。
  • 形状配置:
    • xref='paper'让矩形覆盖整个X轴宽度,无需关心X轴的具体数值范围。
    • layer='below'保证背景不会遮挡折线。
    • opacity调整背景色的透明度,避免影响折线的可读性。
  • 颜色设置:直接通过fillcolor指定要求的#eeeeee和#f5f5f5。

如果你的原有代码已经有折线数据,只需提取Y数据计算均值,然后添加上述shapes配置到update_layout中即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 07:25:58