1

I have a dict of dataframes that I want to use to populate subplots. Each dict has two columns of data for x and y axis, and two categorical columns for hue.

Pseudo code:

for df in dict of dataframes:
    for cat in categories:
        plot(x=col_0, y=col_1, hue=cat)

Data for example:

dict_dfs = dict()
for i in range(5):
    dict_dfs['df_{}'.format(i)] = pd.DataFrame({'col_1':np.random.randn(10), # first column with data = x axis
                                                'col_2':np.random.randn(10), # second column with data = y axis
                                                'cat_0': ('Home '*5 + 'Car '*5).split(), # first category = hue of plots on the left
                                                'cat_1': ('kitchen '*3 + 'Bedroom '*2 + 'Care '*5).split() # second category = hue of plots on the right
                                               }) 

IN:

fig, axes = plt.subplots(len(dict_dfs.keys()), 2, figsize=(15,10*len(dict_dfs.keys())))
for i, (name, df) in enumerate(dict_dfs.items()):
    for j, cat in enumerate(['cat_0', 'cat_1']):
        sns.scatterplot(
            x="col_1", y="col_2", hue=cat, data=df, ax=axes[i,j], alpha=0.6)

        axes[i,j].set_title('df: {}, cat: {}'.format(name, cat), fontsize = 25, pad = 35, fontweight = 'bold')
        axes[i,j].set_xlabel('col_1', fontsize = 26, fontweight = 'bold')
        axes[i,j].set_ylabel('col_2', fontsize = 26, fontweight = 'bold')
        plt.show()

OUT:

the 10 subplots are created correctly (5 dfs * 2 categories), but only the first one (axes[0, 0]) gets populated. I am used to create subplots with one loop, but it's the first time I use two. I have checked the code without finding the issue. Anyone can help ?

3
  • 1
    Does it change if you move the last line (plt.show()) out of the loops (i.e., un-indent it to the beginning of the line)? Commented Jun 7, 2021 at 6:52
  • 1
    it does ! thanks a lot, can you submit it as an answer so I can accept it ? Commented Jun 7, 2021 at 6:55
  • Great, thanks for the feedback, I've added the answer. Commented Jun 7, 2021 at 7:01

1 Answer 1

1

The plt.show() is within the scope of the for-loops, so the figure plot gets shown after the initialization of the first subplot. If you move it out of the loops (un-indent it to the beginning of the line), the plot should correctly be shown with all subplots.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.