停止seaborn在彼此之上绘制多个数字

时间:2016-03-15 17:56:51

标签: python plot seaborn

我开始学习一些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')

3 个答案:

答案 0 :(得分:31)

为了做到这一点,你必须开始一个新的数字。假设您有matplotlib,有多种方法可以做到这一点。同时摆脱get_figure(),您可以从那里使用plt.savefig()

方法1

使用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')

方法2

在每个

之前调用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')

答案 1 :(得分:7)

创建具体数字并绘制到其上:

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')

答案 2 :(得分:1)

我同意先前的评论,即导入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
相关问题