Showing seaborn plot from dictionary

2019-09-03 15:06发布

问题:

I need to store plots in a dictionary like this:

import matplotlib.pyplot as plt
import seaborn as sns

test = dict()
test['a'] = sns.lmplot(x="sepal_length", y="sepal_width", hue="species",
                       truncate=True, height=5, data=sns.load_dataset("iris"))

But how do I show that plot from the dict?

test['a'] returns the plot object like <seaborn.axisgrid.FacetGrid at 0x233011bfe80> but does not show the plot itself.

test['a']
plt.show()

Does not show the plot either.

Any suggestions how to show the plot from the dictionary?

Based on the answer given I tried saving the dict to a pickle file, but showing the plot from pickle gives an error:

import pickle
import matplotlib.pyplot as plt
import seaborn as sns

test = dict()
test['a'] = sns.lmplot(x="sepal_length", y="sepal_width", hue="species",
                       truncate=True, data=sns.load_dataset("iris"))
plt.close()

# store dict in pickle file
outfile = open('test.pkl', 'wb')
pickle.dump(test, outfile)
outfile.close()

# delete dictionary
del test

# load dictionary form pickle file
infile = open('test.pkl', 'rb')
test = pickle.load(infile)
infile.close()

test['a'].fig

回答1:

It seems to suffice to call the associated fig:

test['a'].fig

works for me in a jupyter notebook.

btw: had to remove height parameter

It's not good to change the question entirely. However, it seems that your issue is only related to Jupiter! Check this issue.

One solution is to prepend the first cell with %matplotlib notebook