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)
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)
创建具体数字并绘制到它们上:
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)
| 归档时间: |
|
| 查看次数: |
28130 次 |
| 最近记录: |