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

Plotly make_subplots中Indicator与面积图同子图兼容问题求助

解决Plotly子图中Indicator与Scatter面积图兼容问题

问题根源

Plotly子图的类型对应不同坐标系:

  • indicator类型子图采用domain坐标系,仅支持指标类组件,无法承载依赖笛卡尔坐标系的Scatter轨迹
  • xy类型子图采用笛卡尔坐标系,默认不自动适配Indicator,但通过手动配置Indicator的显示区域,可实现两者共存

解决方案

创建xy类型子图网格,通过domain参数控制Indicator在子图中的显示位置,同时添加Scatter面积图,调整布局让两者组合成独立KPI卡片。

完整代码示例

import plotly.graph_objects as go
from plotly.subplots import make_subplots

# 创建2x2的xy类型子图网格
fig = make_subplots(
    rows=2, cols=2,
    # 显式指定每个子图为xy类型(可选,默认即为xy)
    specs=[[{"type": "xy"} for _ in range(2)] for _ in range(2)],
    # 调整子图间距,让卡片更紧凑
    horizontal_spacing=0.1,
    vertical_spacing=0.1
)

# 模拟KPI数据
kpi_data = [
    {"title": "销售额", "value": 12500, "trend": [8000, 9500, 11000, 12500], "delta": 15},
    {"title": "用户量", "value": 8900, "trend": [6000, 7200, 8100, 8900], "delta": 10},
    {"title": "转化率", "value": 3.2, "trend": [2.5, 2.8, 3.0, 3.2], "delta": 7},
    {"title": "复购率", "value": 45, "trend": [38, 41, 43, 45], "delta": 5}
]

# 为每个子图添加Indicator和Scatter面积图
for idx, data in enumerate(kpi_data, 1):
    row = (idx - 1) // 2 + 1
    col = (idx - 1) % 2 + 1

    # 添加Indicator组件,固定在子图上部
    fig.add_trace(
        go.Indicator(
            mode="number+delta",
            value=data["value"],
            title={"text": data["title"]},
            delta={"reference": data["value"] * (100 - data["delta"]) / 100, "relative": True},
            # 控制Indicator显示区域(子图上30%范围)
            domain={'x': [0, 1], 'y': [0.7, 1]}
        ),
        row=row, col=col
    )

    # 添加Scatter面积图,填充子图下部
    fig.add_trace(
        go.Scatter(
            x=[1, 2, 3, 4],
            y=data["trend"],
            fill='tozeroy',
            line_color="#1f77b4",
            fillcolor="rgba(31, 119, 180, 0.2)",
            showlegend=False
        ),
        row=row, col=col
    )

    # 优化子图样式:隐藏坐标轴、添加边框
    fig.update_xaxes(visible=False, row=row, col=col)
    fig.update_yaxes(visible=False, row=row, col=col)
    fig.update_layout(
        plot_bgcolor="white",
        # 给每个子图添加边框,模拟卡片效果
        shapes=[
            dict(
                type="rect",
                x0=0, y0=0, x1=1, y1=1,
                xref=f"x{idx}", yref=f"y{idx}",
                line=dict(color="#e0e0e0", width=1)
            ) for idx in range(1, 5)
        ]
    )

# 调整整体看板尺寸
fig.update_layout(height=600, width=800, title_text="KPI数据看板")
fig.show()

核心配置说明

  1. 子图类型选择:统一使用xy类型子图,确保Scatter面积图能正常渲染
  2. Indicator位置控制:通过domain参数限定Indicator在子图的上部区域,避免与面积图重叠
  3. 样式优化:隐藏坐标轴、添加边框,让每个子图呈现独立卡片的视觉效果
  4. 数据适配:可根据业务需求调整Indicator的mode(如添加gauge模式)和Scatter的趋势数据源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 11:30:10