Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save multiple plot in a loop?

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)
like image 573
parvij Avatar asked Nov 01 '25 22:11

parvij


1 Answers

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()
like image 177
roganjosh Avatar answered Nov 03 '25 11:11

roganjosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!