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

Plotly多列子图实现问题求助

Plotly多列子图实现问题求助

嗨,我看了你遇到的子图问题啦,问题出在你用update_traces的方式不对——这个方法是用来修改已存在的trace属性的,不是用来添加新trace的!你每个子图需要的三条曲线,都得用add_trace来逐个添加才行。

我给你调整一下代码,解决这个问题,同时还能保留你原函数里的那些好用的特性(比如统一hover模式):

首先,先整理一下循环逻辑,确保每个子图位置都正确添加三个trace:

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

# 定义子图的行列数
r = 2
c = 2
# 随机选取要展示的商品
sample_items = random.sample(grand_aggregate['wh_item_code'].unique().tolist(), r*c)

# 创建子图布局,可设置每个子图的标题,还能选择共享轴优化布局
sub_fig = make_subplots(
    rows=r, cols=c,
    subplot_titles=[f"Item: {item}" for item in sample_items],
    shared_xaxes=True,  # 共享X轴让整体布局更整洁
    shared_yaxes=False  # 价格和百分比差异量级不同,不共享Y轴更合理
)

# 遍历每个商品和对应的子图位置
for idx, item in enumerate(sample_items):
    # 计算当前子图的行和列(Plotly的行/列从1开始计数)
    row = (idx // c) + 1
    col = (idx % c) + 1
    
    # 提前筛选当前商品的数据,避免重复写筛选条件
    item_df = grand_aggregate[grand_aggregate['wh_item_code'] == item]
    
    # 逐个添加三条曲线到对应子图
    # 1. list_price曲线
    sub_fig.add_trace(
        go.Scatter(
            x=item_df['vpl_start_week'],
            y=item_df['list_price'],
            mode='lines',
            name='list_price',
            legendgroup='list_price'  # 图例分组,避免同一系列重复显示
        ),
        row=row, col=col
    )
    
    # 2. current_sell_zone1曲线
    sub_fig.add_trace(
        go.Scatter(
            x=item_df['vpl_start_week'],
            y=item_df['current_sell_zone1'],
            mode='lines',
            name='current_sell_zone1',
            legendgroup='current_sell_zone1'
        ),
        row=row, col=col
    )
    
    # 3. percentile_difference曲线
    sub_fig.add_trace(
        go.Scatter(
            x=item_df['vpl_start_week'],
            y=item_df['percentile_difference'],
            mode='lines',
            name='percentile_difference',
            legendgroup='percentile_difference'
        ),
        row=row, col=col
    )

# 设置整体布局和统一的hover模式
sub_fig.update_layout(
    height=900,
    width=1200,
    title_text="Item Price Analysis Subplots",
    hovermode="x unified",  # 和原函数一致的hover交互体验
    legend=dict(
        orientation="h",
        yanchor="bottom",
        y=1.02,
        xanchor="right",
        x=1  # 把图例放在顶部右侧,避免遮挡子图内容
    )
)

# 给子图设置轴标签(只给边缘的轴加标签,避免重复)
sub_fig.update_xaxes(title_text="vpl_start_week", row=r, col=1)
sub_fig.update_yaxes(title_text="Price / Difference", row=1, col=1)

sub_fig.show()

关键修正点说明:

  • 替换update_traces为add_trace:每个子图的三条曲线都需要单独添加,update_traces是用来修改已有trace样式的,不能用来新增trace。
  • 提前筛选数据:通过item_df把当前商品的数据一次性筛选出来,让代码更简洁易读。
  • 图例分组:用legendgroup让同一类型的曲线在图例中只显示一次,不会因为子图数量多而重复出现。
  • 优化布局细节:添加子图标题、共享X轴、调整图例位置,让子图更美观易用。

这样修改后,你的子图应该就能正常显示每个商品的三条曲线了,效果和你原函数生成的单图一致,只是排列成了你想要的子图布局。

备注:内容来源于stack exchange,提问作者Sanjeev Kallepalli

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.20 11:14:28