简体   繁体   中英

seaborn distplot loop lazy evaluation

I am using ipython notebook and trying to use the following function to export seaborn distplots. It works just fine if I call the function and execute with only one variable at a time. If I call the function in a loop, it continues to build on top of the distplot from the previous function call.

My desired output would be for the function to output a new displot every time it is called in a loop. Is there a way to force evaluation or a new distplot?

def graph_extraversion (x):


    file_name = "extraversion_" + str(x) + ".png"
    sns_plot = sns.distplot(Personalities[Personalities.labels1 ==x].extraversion)
    sns_plot = sns.distplot(df.extraversion)
    fig = sns_plot.get_figure()
    fig.savefig(file_name)
    new_stat = Personalities[Personalities.labels1 ==x].extraversion.describe()
    extraversion_drift = extraversion_median - new_stat[1]
    drift = extraversion_drift / extraversion_std
    if (drift >= 1) | (drift <= -1):
        return "1 std deviation or more"
    else:
        return "Less than one std deviation"

This what is what the distplot looks like after one call

在此处输入图片说明

This is two calls later in a loop.

在此处输入图片说明

Again this works just fine with a single call and execution but when looped it keeps building.

So this has to do with matplotlib and closing figures.

additional code required is an import:

import matplotlib.pyplot as plt

Then at the end of the func:

plt.close(fig)

This should help with any looping with both seaborn and matplotlib

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM