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

Ale*_*lex 24 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')
Run Code Online (Sandbox Code Playgroud)

Leb*_*Leb 42

你必须开始一个新的数字才能做到这一点.假设你有多种方法可以做到这一点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')
Run Code Online (Sandbox Code Playgroud)

方法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')
Run Code Online (Sandbox Code Playgroud)

  • 这个答案是“可行的”,但由于它依赖于matplotlib状态机接口而不是完全采用面向对象的接口,因此它不是首选的IMO。快速绘图是很好的选择,但是在复杂性缩放的某个时候,最好使用后者。 (3认同)

MF.*_*.OX 15

我同意之前的评论,导入matplotlib.pyplot不是最好的软件工程实践,因为它暴露了底层库。当我在循环中创建和保存绘图时,我需要清除图形并发现现在只需导入即可轻松完成seaborn

从 0.11 版开始:

import seaborn as sns
import numpy as np

data = np.random.normal(size=100)
path = "/path/to/img/plot.png"

plot = sns.displot(data) # also works with histplot() etc
plot.fig.savefig(path)
plot.fig.clf() # this clears the figure

# ... continue with next figure
Run Code Online (Sandbox Code Playgroud)

带有循环的替代示例:

import seaborn as sns
import numpy as np

for i in range(3):
  data = np.random.normal(size=100)
  path = "/path/to/img/plot2_{0:01d}.png".format(i)

  plot = sns.displot(data)
  plot.fig.savefig(path)
  plot.fig.clf() # this clears the figure
Run Code Online (Sandbox Code Playgroud)

0.11 版之前(原帖):

import seaborn as sns
import numpy as np

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
Run Code Online (Sandbox Code Playgroud)


mwa*_*kom 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')
Run Code Online (Sandbox Code Playgroud)