How can a graph created in Python be saved?
In Python, you can save the plotted figure as a file using the savefig method. Below is an example code for saving the figure.
import matplotlib.pyplot as plt
# 绘制图形
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.xlabel('x轴')
plt.ylabel('y轴')
plt.title('示例图形')
# 保存图形为文件
plt.savefig('图形.png') # 保存为PNG格式
plt.savefig('图形.jpg') # 保存为JPEG格式
plt.savefig('图形.pdf') # 保存为PDF格式
# 关闭图形
plt.close()
In the above code, the graphics are saved by specifying the file name and format using the savefig method. Different file formats can be chosen based on the requirements for saving the graphics. The saved graphics file will be located in the same directory as the Python script file.