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

Matplotlib调用savefig()导出Jupyter内正常显示的绘图为空白图片问题

问题原因

你的代码中plt.figure(figsize=(3, 3))的调用顺序错误:所有绘图逻辑(散点绘制、曲线拟合、坐标轴/标题设置)都在默认生成的画布上完成后,你才新建了一张尺寸为3*3的空白画布,后续plt.savefig操作默认保存最新创建的画布,自然就是空白图。
Jupyter Notebook 中能正常显示是因为plt.show()会渲染所有未关闭的画布,你看到的是绘图操作对应的旧画布,并非你保存的那张新空白画布。

修复方案

将plt.figure(figsize=(3, 3))移到每轮循环的最开头,也就是所有绘图操作执行之前即可。同时建议在每轮循环结束后添加plt.close()释放画布资源,避免内存堆积。

修正后的核心代码如下:

munilist = ["Adjuntas", "Anasco", "Ciales", "Jayuya", "Lares", "LasMarias", "Maricao", "Mayaguez", "Orocovis", "Penuelas", "Ponce", "SabanaGrande", "SanGerman", "SanSebastian", "Utuado", "Yauco"]
for municipality in munilist:
    # 调整顺序:先创建指定尺寸的画布,再执行绘图操作
    plt.figure(figsize=(3, 3))
    
    x = np.array([1987, 1992, 1998, 2002, 2007, 2012]).reshape(6,1)
    y = np.array(df[df["Municipio"]==municipality].iloc[0, 1:7]).reshape(6,1)
    print(y)
    mask = ~pd.isnull(y) # 过滤CSV中的空值
    print(mask)
    xlin = np.arange(1987, 2013,1) # 绘图年份范围
    reg = LinearRegression(fit_intercept=True).fit(x[mask].reshape(-1,1), y[mask])
    a0 = reg.intercept_
    a1 = reg.coef_[0]

    fit = a0 + a1*xlin # 拟合值

    b0 = float(a0) # f字符串不支持数组格式,转换为浮点型
    b1 = float(a1)
    eq = f"$farms = ${b0:.3f} $+$ {b1:.3f}$*year$"

    plt.scatter(x,y, label = name)
    plt.title(municipality)
    plt.plot(xlin, fit, 'r', label = "拟合线")
    plt.xlabel("年份")
    plt.ylabel(name)
    plt.text(2000,1000, eq)
    plt.legend()
    
    if not os.path.isdir("RegressionsOutput/" + municipality):
        os.makedirs("RegressionsOutput/" + municipality)
    plt.savefig("RegressionsOutput/" + municipality + "/" + name + '.png', format="png", dpi=300, bbox_inches = 'tight') 
    plt.show()
    plt.close() # 关闭当前画布,释放资源

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:06:04