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

使用pandas的df.plot绘制多图时为何仅显示最后一张?

批量绘制独立柱状图的问题解决

原实现代码

我编写了用于绘制DataFrame柱状图的bar_plot_vuelos函数,代码如下:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('dataset_SCL.csv', parse_dates=parse_dates, low_memory=False)

def bar_plot_vuelos(var1: str, var2: str, plot_type: str, plot_title: str, y_label: str, x_label: str) -> pd.DataFrame.plot:
    """
    返回柱状图对象
    """
    df_groups = df.groupby(var1)[var2].sum()
    df_groups.plot(kind=plot_type)
    bar_plot = df_groups.plot(kind=plot_type, title=plot_title, ylabel=y_label, xlabel=x_label, figsize=(25, 9), stacked=True)
    return bar_plot

遇到的问题

函数本身可正常运行,但连续调用三次生成三张图表时:

# 注:原调用语句中的西语标题已译为中文
plot1 = bar_plot_vuelos('SIGLADES', 'Atraso', 'bar', '目的地延误总量', '延误数量', '目的地')
plot2 = bar_plot_vuelos('OPERA', 'Atraso', 'bar', '航空公司延误总量', '延误数量', '航空公司')
plot3 = bar_plot_vuelos('MES', 'Atraso', 'bar', '月度延误总量', '延误数量', '月份')

实际运行后仅能看到最后一张图表,前两张被覆盖无法显示。

解决方法

在函数中添加plt.figure()语句,每次调用时创建新的绘图画布,修改后的函数代码如下:

def bar_plot_vuelos(var1: str, var2: str, plot_type: str, plot_title: str, y_label: str, x_label: str) -> pd.DataFrame.plot:
    """
    返回柱状图对象
    """
    df_groups = df.groupby(var1)[var2].sum()
    plt.figure()  # 新增:创建新的独立画布
    df_groups.plot(kind=plot_type)
    bar_plot = df_groups.plot(kind=plot_type, title=plot_title, ylabel=y_label, xlabel=x_label, figsize=(25, 9), stacked=True)
    return bar_plot

修改后再次调用函数,三个图表会作为独立窗口(或子图)全部正常显示。

核心原因

pandas的plot方法默认在当前活跃的matplotlib画布上绘制内容,连续调用时后续绘图会覆盖之前的内容。添加plt.figure()会强制创建新的画布,让每个图表都拥有独立的绘图空间,避免被覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 06:00:48