How to save multiple plot in a loop?

2019-03-04 12:35发布

I tried to save multiple plot in a loop, but It draw them over each other. what should I do?

sample code:

import pandas as pd
import seaborn as sns
data=pd.DataFrame({'a':[1,2,3,4,5,6],'b':[0,1,1,0,1,1],'c':[0,0,0,1,1,1]})
for i in ['b','c']:
    img=sns.boxplot(data.a, groupby=data[i])
    fig = img.get_figure()
    fig.savefig(i)

1条回答
看我几分像从前
2楼-- · 2019-03-04 12:55

You need to clear the data from the previous figure which is rolling over in the loop. This should work, noting fig.clf() as the end of each loop:

import pandas as pd
import seaborn as sns
data=pd.DataFrame({'a':[1,2,3,4,5,6],'b':[0,1,1,0,1,1],'c':[0,0,0,1,1,1]})
for i in ['b','c']:
    img=sns.boxplot(data.a, groupby=data[i])
    fig = img.get_figure()
    fig.savefig(i)
    fig.clf()
查看更多
登录 后发表回答