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. 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
CodePudding user response:
You're calling plt.figure(figsize=...)
after having done all of the work. 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.
plt.figure()
is designed to be used to create a new figure, so you will be overwriting any work you've done.
CodePudding user response:
You should explicitly define the figure (e.g. "fig") initially (i.e. prior to 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', ...)