我正在尝试将 Matplotlib 中的图形保存到文件中,但是当我运行命令来保存图像时,它不会给出任何错误,但我看不到该文件。
plt.savefig('Traveling Salesmen Graph.png')
Run Code Online (Sandbox Code Playgroud)
pyplot 跟踪“当前图形”,并且在需要图形的库上调用的函数对其进行操作,但您也可以通过调用savefig()图形对象来更明确。
作为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')
Run Code Online (Sandbox Code Playgroud)
以这种方式明确应该可以解决您的问题。
有关对“当前图形”进行操作的 pyplot 函数的参考,请参阅: https: //matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.html