简体   繁体   English

如何在 Python 中的 Matplotlib 中保存图形

[英]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.我正在尝试将 Matplotlib 中的图形保存到文件中,但是当我运行命令保存图像时,它没有给出任何错误,但我看不到文件。

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. pyplot 跟踪“当前图形”,并在库上调用需要图形的函数对其进行操作,但您也可以通过在图形 object 上调用savefig()来更明确。

as an example from https://pythonspot.com/matplotlib-save-figure-to-image-file/ :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有关在“当前图”上运行的 pyplot 函数的参考,请参阅:https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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