Why did I get 2 plots in Jupyter Notebook?

Screen Link:
I like to practice writing the code from the Dataquest lessons in my own Jupyter Notebook, but in this case, I’m getting two heatmaps when I run the correct lesson solution in my Jupyter Notebook.

Screen Link:
https://app.dataquest.io/m/370/working-with-missing-data/5/visualizing-missing-data-with-plots

Here’s my code:

def plot_null_correlations(df):
    # create a correlation matrix only for columns with at least
    # one missing value
    cols_with_missing_vals = df.columns[df.isnull().sum() > 0]
    missing_corr = df[cols_with_missing_vals].isnull().corr()
    
    # create a triangular mask to avoid repeated values, 
    # self-correlation on the main diagonal and
    # make the plot easier to read
    missing_corr = missing_corr.iloc[1:, :-1]
    mask = np.triu(np.ones_like(missing_corr), k=1)
    
    # plot a heatmap of the values
    plt.figure(figsize=(20,14))
    ax = sns.heatmap(missing_corr, vmin=-1, vmax=1, cbar=False,
                     cmap='RdBu', mask=mask, annot=True)
    
    plt.figure(figsize=(20,14))
    ax = sns.heatmap(missing_corr, vmin=-1, vmax=1, cbar=False,
                     cmap='RdBu', mask=mask, annot=True)
    
    # format the text in the plot to make it easier to read
    for text in ax.texts:
        t = float(text.get_text())
        if -0.05 < t < 0.01:
            text.set_text('')
        else:
            text.set_text(round(t, 2))
        text.set_fontsize('x-large')
    plt.xticks(rotation=90, size='x-large')
    plt.yticks(rotation=0, size='x-large')
    
    plt.show()

vehicle_cols = [col for col in mvc.columns if 'vehicle' in col]
mvc_vehicle = mvc[vehicle_cols]
plot_null_correlations(mvc_vehicle)

What I get on the Dataquest platform:
Screen Shot 2020-03-28 at 8.02.34 AM

What I get in Jupyter Notebook:

Is this a setting issue? I’ve found Jupyter Notebook to give unexpected results with plots–for example, this and generating a plot without having to do plt.show().

1 Like

Hi @quinones,

You are creating the figure object two times in your code:

plt.figure(figsize=(20,14))
ax = sns.heatmap(missing_corr, vmin=-1, vmax=1, cbar=False,
                 cmap='RdBu', mask=mask, annot=True)
    
plt.figure(figsize=(20,14))
ax = sns.heatmap(missing_corr, vmin=-1, vmax=1, cbar=False,
                 cmap='RdBu', mask=mask, annot=True)

Remove one of them and it will display one plot.

Best,
Sahil

3 Likes