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

Plotly循环创建子图时标题与子图不匹配问题修复求助

修复Plotly子图标题与内容不匹配的问题

问题原因

你代码里的子图列索引计算逻辑错误,导致图表填充顺序和标题顺序完全错位:

  • subplot_titles 用sorted(df['Region'].unique())生成的标题,是按排序后顺序从上到下、从左到右排列的
  • 但你通过math.ceil(i%2)+1计算列索引时,会让图表先填充右侧列、再填充左侧列(比如i=1对应col=2,i=2对应col=1),最终标题和对应区域的图表完全不匹配。

修复方案

修正列索引计算逻辑,让图表按照从上到下、从左到右的顺序填充,和标题顺序保持一致:

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

fig = make_subplots(rows=6, cols=2, subplot_titles=sorted(df['Region'].unique()))
for i, region in enumerate(sorted(df['Region'].unique()), start=1):
    data = df.query('Region==@region').sort_values(by='Population', ascending=False)
    mytrace = go.Bar(x=data['Country'], y=data['Population'], name=region)
    # 修正行列计算:行号保持不变,列号改为从左到右依次填充
    row = math.ceil(i / 2)
    col = (i - 1) % 2 + 1  # 关键修复:i=1→col1,i=2→col2,i=3→col1,以此类推
    fig.add_trace(mytrace, row=row, col=col)
fig.update_layout(width=1500, height=2250)

原理说明

(i - 1) % 2 + 1 会让从1开始的索引i对应正确的列位置:

  • 第1、3、5...个区域 → 对应子图左列(col=1)
  • 第2、4、6...个区域 → 对应子图右列(col=2)
    这样图表的填充顺序和subplot_titles里的标题顺序完全对齐,就能解决标题与内容不匹配的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 16:30:43