如何在 Matplotlib 中更改“保存图片”的默认路径?
要更改“保存图片”的默认路径,我们可以使用 rcParams["savefig.directory"] 来设置目录路径。
步骤
- 设置图形大小和调整子图之间和周围的填充。
- 使用 numpy 创建随机数据。
- 使用 imshow() 方法。将数据显示为图像,即,在 2D 规则光栅上。
- 使用 plt.savefig() 方法保存图形。
示例
import os import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True dir_name = "C:/Windows/Temp/" plt.rcParams["savefig.directory"] = os.chdir(os.path.dirname(dir_name)) data = np.random.rand(5, 5) plt.imshow(data, cmap="copper") plt.savefig("img.png")
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
输出
当我们执行代码时,它会将以下绘图以“img.png”保存到指定的路径:“C:/Windows/Temp/”
广告