简体   繁体   English

Matplotlib savefig() 将绘图保存为空白图像

[英]Matplotlib savefig() saving plots as blank images

I'm trying to save graphs in folders I'm creating and they all show within Jupyter notebook but save as blank images within my folders.我正在尝试将图表保存在我正在创建的文件夹中,它们都显示在 Jupyter 笔记本中,但在我的文件夹中另存为空白图像。 This is my code:这是我的代码:

    munilist = ["Adjuntas", "Anasco", "Ciales", "Jayuya", "Lares", "LasMarias", "Maricao", "Mayaguez", "Orocovis", "Penuelas", "Ponce", "SabanaGrande", "SanGerman", "SanSebastian", "Utuado", "Yauco"]
    for municipality in munilist:
        
        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) #creating a mask to get rid of NaN columns values in certain csvs
        print(mask)
        xlin = np.arange(1987, 2013,1) #range of years to plot
        reg = LinearRegression(fit_intercept=True).fit(x[mask].reshape(-1,1), y[mask])
        a0 = reg.intercept_
        a1 = reg.coef_[0]

        fit = a0 + a1*xlin #fitted value

        b0 = float(a0) #f strings do not accept array. Need to convert to float
        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 = "fitted line")
        plt.xlabel("Year")
        plt.ylabel(name)
        plt.text(2000,1000, eq)
        plt.legend()
        plt.figure(figsize=(3, 3)) #had to change figure size because they were coming out way too large
        if not os.path.isdir("RegressionsOutput/" + municipality):
            os.makedirs("RegressionsOutput/" + municipality)
        plt.savefig("RegressionsOutput/" + municipality + "/" + name + '.png', format="png", dpi=300, bbox_inches = 'tight') #save before showing
        plt.show()

This is what saves in my folders这是保存在我的文件夹中的内容

You're calling plt.figure(figsize=...) after having done all of the work.完成所有工作后,您正在调用plt.figure(figsize=...) This will reset the figure.这将重置数字。 Just move this line to the top so that it looks like只需将此行移到顶部,使其看起来像

eq = f"..."
plt.figure(figsize=(3,3))
...
plt.savefig(...)

I'm 95% sure this is your problem.我有 95% 的把握这是你的问题。

plt.figure() is designed to be used to create a new figure, so you will be overwriting any work you've done. plt.figure()旨在用于创建图形,因此您将覆盖您所做的任何工作。

You should explicitly define the figure (eg "fig") initially (ie prior to plt.scatter()):您应该最初明确定义图形(例如“fig”)(即在 plt.scatter() 之前):

fig = plt.figure(figsize=(3, 3), num=1, clear=True)

and then show:然后显示:

plt.show()

and then save:然后保存:

fig.savefig("RegressionsOutput/" + municipality + "/" + name + '.png', ...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM