how to display multiple correlation heatmaps in a loop using pandas?

Question:

I found this post to display correlation heatmap very easily just using pandas. This approach only work to show one heatmap in jupyter notebook. Now I’d like to display multiple dataframe in a loop using jupyter notebook. How to do it? It didn’t show any at all. If I use print(), it will only show it is pandas styler object.

Plot correlation matrix using pandas

Now I define this heatmap into a function, then later I will use it inside a loop.


def heatmap_pandas(corr):
    mask = np.zeros_like(corr, dtype=bool)
    mask[np.tril_indices_from(mask)] = True  
    corr[mask] = np.nan
    (corr
     .style
     .background_gradient(cmap='coolwarm', axis=None, vmin=-1, vmax=1)
     .highlight_null(null_color='#f1f1f1')  # Color NaNs grey
     .set_precision(2))

for corr in [corr_1,corr_2,corr_3]:
    heatmap_pandas(df_time_corr)

The above didn’t show any heatmap at all. I understand since it was designed to work on jupyter notebook cell by cell. I like this approach, so how to make it work inside a loop? Thanks

Asked By: roudan

||

Answers:

In Jupyter notebook, you can force display an item inside a for loop with display. So in your case, you can do:

def heatmap_pandas(corr):
    mask = np.zeros_like(corr, dtype=bool)
    mask[np.tril_indices_from(mask)] = True  
    corr[mask] = np.nan

    # display the styler
    display(corr       
     .style
     .background_gradient(cmap='coolwarm', axis=None, vmin=-1, vmax=1)
     .highlight_null(null_color='#f1f1f1')  # Color NaNs grey
     .set_precision(2))

for corr in [corr_1,corr_2,corr_3]:
    heatmap_pandas(df_time_corr)
Answered By: Quang Hoang
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.