Why is my plt.savefig is not working?

Question:

I have a simple python code as follows:

import numpy as np
import matplotlib.pyplot as plt

"""
Here are the solutions and the plot.
"""

# Create the axis and plot.
plt.axis([0, 10, 0, 10])
axis_x = range(1, 11)
grd = [1.1, 2.1, 3.1, 4.1, 5.1, 6.1, 7.1, 8.1, 9.1, 10.1]
grd2 = [1.2, 2.2, 3.2, 4.2, 5.2, 6.2, 7.2, 8.2, 9.2, 10.2]
plt.plot(axis_x, grd, '-g', label='BR1')
plt.plot(axis_x, grd2, '-b', label='BR2')
plt.legend(loc='upper left')
plt.grid()
plt.show()

# Save the results vector to a text file.
np.savetxt('test.out', (grd, grd2))

# Save the figure as '.eps' file.
plt.savefig('expl.pdf', format='pdf', dpi=1200)

When I open the output files expl.pdf and/or test.out I find them blank and nothing in there. Why?

Thanks.

Asked By: Jika

||

Answers:

Your plot cannot be generated because you defined the list axis_x having only the length 9, while grd and grd2 have the length equal to 10.
Just replace the definition of axis_x with:

axis_x=range(1,11)
and your plot will show up and it will be saved OK.

Answered By: xecafe

When you close the image displayed by plt.show(), the image is closed and freed from memory.

You should call savefig and savetxt before calling show.

Answered By: shx2

I just ran into the same issue and the resolution was to put the savefig command before the plt.show() statement, but specify the filetype explicitly. Here is my code:

plt.suptitle("~~~~")
plt.title("~~~~")
ax = sns.boxplot(x=scores_df.score, y=scores_df.response)
plt.savefig("test.png", format="png") # specify filetype explicitly
plt.show()

plt.close()
Answered By: bmc
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.