Python 停止 seaborn 将多个数字叠加在一起
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36018681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stop seaborn plotting multiple figures on top of one another
提问by Alex
I'm starting to learn a bit of python (been using R) for data analysis. I'm trying to create two plots using seaborn
, but it keeps saving the second on top of the first. How do I stop this behavior?
我开始学习一些用于数据分析的 Python(一直在使用 R)。我正在尝试使用创建两个图seaborn
,但它一直将第二个保存在第一个之上。我如何停止这种行为?
import seaborn as sns
iris = sns.load_dataset('iris')
length_plot = sns.barplot(x='sepal_length', y='species', data=iris).get_figure()
length_plot.savefig('ex1.pdf')
width_plot = sns.barplot(x='sepal_width', y='species', data=iris).get_figure()
width_plot.savefig('ex2.pdf')
回答by Leb
You have to start a new figure in order to do that. There are multiple ways to do that, assuming you have matplotlib
. Also get rid of get_figure()
and you can use plt.savefig()
from there.
你必须开始一个新的数字才能做到这一点。有多种方法可以做到这一点,假设您有matplotlib
. 也摆脱,get_figure()
你可以plt.savefig()
从那里使用。
Method 1
方法一
Use plt.clf()
import seaborn as sns
import matplotlib.pyplot as plt
iris = sns.load_dataset('iris')
length_plot = sns.barplot(x='sepal_length', y='species', data=iris)
plt.savefig('ex1.pdf')
plt.clf()
width_plot = sns.barplot(x='sepal_width', y='species', data=iris)
plt.savefig('ex2.pdf')
Method 2
方法二
Call plt.figure()
before each one
plt.figure()
在每一个之前打电话
plt.figure()
length_plot = sns.barplot(x='sepal_length', y='species', data=iris)
plt.savefig('ex1.pdf')
plt.figure()
width_plot = sns.barplot(x='sepal_width', y='species', data=iris)
plt.savefig('ex2.pdf')
回答by MF.OX
I agree with a previous comment that importing matplotlib.pyplot
is not the best software engineering practice as it exposes the underlying library. As I was creating and saving plots in a loop, then I needed to clear the figure and found out that this can now be easily done by importing seaborn
only:
我同意之前的评论,导入matplotlib.pyplot
不是最好的软件工程实践,因为它暴露了底层库。当我在循环中创建和保存绘图时,我需要清除图形并发现现在只需导入即可轻松完成seaborn
:
import seaborn as sns
data = np.random.normal(size=100)
path = "/path/to/img/plot.png"
plot = sns.distplot(data)
plot.get_figure().savefig(path)
plot.get_figure().clf() # this clears the figure
# ... continue with next figure
回答by mwaskom
Create specific figures and plot onto them:
创建特定图形并在其上绘图:
import seaborn as sns
iris = sns.load_dataset('iris')
length_fig, length_ax = plt.subplots()
sns.barplot(x='sepal_length', y='species', data=iris, ax=length_ax)
length_fig.savefig('ex1.pdf')
width_fig, width_ax = plt.subplots()
sns.barplot(x='sepal_width', y='species', data=iris, ax=width_ax)
width_fig.savefig('ex2.pdf')