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

如何解决Matplotlib绘制子图时坐标轴重复显示的问题

问题原因

你代码里的坐标轴重复是两个错误操作叠加导致的:

  1. 先执行了fig, ax = plt.subplots(5,2,figsize=(20,10)),提前创建了5行2列共10个空白子图坐标轴
  2. 后续循环里又调用fig.add_subplot(2, 2, i),在原有画布上额外叠加了4个新的子图,原先的10个空白坐标轴没有被覆盖,就出现了重复打印的问题

修复方案

直接修改子图创建逻辑即可,不需要提前创建多余的5*2子图,你只需要展示TOP4的商品,直接创建2行2列的子图数组,循环对应索引绘图就好,修复后代码如下:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

Cat = ['A', 'B', 'C']
It = ['D', 'E', 'F','G','H','I','J']
n=365
df = pd.DataFrame({'Category': np.random.choice(Cat, n ),
                   'Item': np.random.choice(It, n ),
                  'Net sales':np.random.randint(100,500,(n)),
                      'Date':np.random.choice( pd.date_range('1/1/2021', periods=365,
                          freq='D'), n, replace=False)})
# 计算销售额TOP4的商品
prod_sales = df.groupby('Item')['Net sales'].sum().sort_values(ascending=False)
top4_items = prod_sales.head(4).index.tolist()

# 直接创建2行2列的子图,对应4个TOP商品
fig, axs = plt.subplots(2, 2, figsize=(20,10))
# 把子图数组展平方便循环索引
axs = axs.flatten()

for idx, item in enumerate(top4_items):
    # 筛选对应商品的数据
    group = df[df['Item'] == item]
    group.plot(x='Date', y='Net sales', ax=axs[idx], label=item, title=f'商品{item}销售趋势')

plt.tight_layout() # 自动调整子图间距避免重叠
plt.show()

额外优化点

  • 提前筛选TOP4商品列表,避免循环内做判断,逻辑更清晰、执行效率更高
  • 新增plt.tight_layout()自动调整子图间距,避免标题、坐标轴标签重叠
  • 为每个子图添加专属标题,可读性更好

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:18:01