4

I am trying to save my figure in Matplotlib to a file but when I run the command to save the image, it doesn't give any errors but I can't see the file.

plt.savefig('Traveling Salesmen Graph.png')
5
  • Please check for it in your current working directory Commented Jul 13, 2020 at 3:27
  • plt.savefig() goes before plt.show() Commented Jul 13, 2020 at 3:28
  • @TrentonMcKinney I don't have a plt.show() I just have a plt.plot() Commented Jul 13, 2020 at 3:32
  • Please provide a Provide a Minimal, Reproducible Example (e.g. code, data, errors) as text Commented Jul 13, 2020 at 3:33
  • @SpideyZac It might help to save the file to a specific location and check there. When I ran your command, the figure is saved to the working directory. Commented Jul 13, 2020 at 3:35

1 Answer 1

9

pyplot keeps track of the "current figure", and functions called on the library which require a figure operate on that, but you can also be more explicit by calling savefig() on the figure object.

as an example from https://pythonspot.com/matplotlib-save-figure-to-image-file/:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

y = [2,4,6,8,10,12,14,16,18,20]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
plt.title('Legend inside')
ax.legend()
#plt.show()

fig.savefig('plot.png')

Being explicit in this way should solve your issue.

For references to pyplot functions which operate on the "current figure" see: https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.html

Sign up to request clarification or add additional context in comments.

2 Comments

plt.savefig is very much a thing. This is not factually correct
@MadPhysicist You're right, I've modified the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.