你可以使用以下语法将Seaborn绘图保存到一个文件中。
import seaborn as sns
line_plot = sns.lineplot(x=x, y=y)
fig = line_plot.get_figure()
fig.savefig('my_lineplot.png')
下面的例子展示了如何在实践中使用这种语法。
例1:将Seaborn绘图保存到PNG文件中
下面的代码显示了如何将Seaborn绘图保存到PNG文件中。
import seaborn as sns
#set theme style
sns.set_style('darkgrid')
#define data
x = [1, 2, 3, 4, 5, 6]
y = [8, 13, 14, 11, 16, 22]
#create line plot and save as PNG file
line_plot = sns.lineplot(x=x, y=y)
fig = line_plot.get_figure()
fig.savefig('my_lineplot.png')
如果我们导航到我们保存文件的位置,我们就可以查看它。
请注意,我们也可以使用**.jpg**、.pdf或其他文件扩展名来保存绘图到不同类型的文件。
例子2:将Seaborn绘图保存为PNG文件,并进行严格的排版
默认情况下,Seaborn会在图的外部添加填充物。
要删除这个填充,我们可以使用bbox_inches='tight'参数。
fig.savefig('my_lineplot.png', bbox_inches='tight')
请注意,现在图的外部有最小的填充。
例3:将Seaborn图保存为自定义尺寸的PNG文件
你可以使用dpi参数来增加Seaborn图在保存到文件时的尺寸。
fig.savefig('my_lineplot.png', dpi=100)
请注意,这个图比前两个图要大得多。你使用的dpi值越大,绘图就越大。
其他资源
下面的教程解释了如何在Seaborn中执行其他常见的绘图功能。
如何在一个图中创建多个Seaborn图
如何调整Seaborn图的图大小
如何为Seaborn图添加标题
The postHow to Save Seaborn Plot to a File (With Examples) appeared first onStatology.