Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save figure in Matplotlib in Python [duplicate]

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')
like image 837
Spidey Zac Avatar asked Oct 29 '25 05:10

Spidey Zac


1 Answers

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

like image 140
Mark McElroy Avatar answered Oct 31 '25 11:10

Mark McElroy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!