简体   繁体   中英

How to save figure in Matplotlib in Python

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')

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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