你可以使用以下基本语法将Matplotlib图形保存到一个文件中。
import matplotlib.pyplot as plt
#save figure in various formats
plt.savefig('my_plot.png')
plt.savefig('my_plot.jpg')
plt.savefig('my_plot.pdf')
下面的例子展示了如何在实践中使用这种语法。
例1:将Matplotlib图保存到PNG文件中
下面的代码展示了如何将一个Matplotlib图保存到PNG文件中。
import matplotlib.pyplot as plt
#define data
x = [1, 2, 3, 4, 5, 6]
y = [8, 13, 14, 11, 16, 22]
#create scatterplot with axis labels
plt.plot(x, y)
plt.xlabel('X Variable')
plt.ylabel('Y Variable')
#save figure to PNG file
plt.savefig('my_plot.png')
如果我们导航到我们保存文件的位置,我们就可以查看它。
例子2:保存Matplotlib图,并进行严格的排版
默认情况下,Matplotlib会在图的外部添加大量的填充物。
要去除这个填充,我们可以使用bbox_inches='tight'参数。
#save figure to PNG file with no padding
plt.savefig('my_plot.png', bbox_inches='tight')
注意,在图的外部有较少的填充物。
例3:用自定义尺寸保存Matplotlib图形
你也可以在保存Matplotlib图形时使用dpi参数来增加它的尺寸。
#save figure to PNG file with increased size
plt.savefig('my_plot.png', dpi = 100)
你可以在这里找到Matplotlib**savefig()**函数的完整在线文档。
其他资源
下面的教程解释了如何在Matplotlib中执行其他常用函数。
如何在Matplotlib中设置轴的范围
如何在Matplotlib中增加图的大小
如何在一个图中创建多个Matplotlib图
The postHow to Save Matplotlib Figure to a File (With Examples)appeared first onStatology.