PyCharm: How to display multiple plots with plt.show()?

Viewed 3724

I used plt.show() in different parts of the code to show some figures. But with each execution of the command plt.show(), the execution will only continue after closing the current figure. How can I show figures without having to close the current one (to see all)?

Example:

import pandas as pd 
import seaborn as sn
import matplotlib.pyplot as plt
    
data = {'A': [45, 31, 42, 35, 39], 
        'B': [38, 31, 26, 28, 33], 
        'C': [10, 15, 17, 21, 12], 
        'D': [9, 14, 16, 22, 141]} 
df = pd.DataFrame(data, columns=['A', 'B'])
corrMatrix = df.corr()
sn.heatmap(corrMatrix, annot=True)
    
plt.show()  # this should be closed to continue
    
df = pd.DataFrame(data, columns=['C', 'D'])
corrMatrix = df.corr()
sn.heatmap(corrMatrix, annot=True)
    
plt.show()

BTW I'm using PyCharm on macOS.

1 Answers

The comments from @SimonFromme are correct:

  • you create the figures and then call plt.show only once
  • this doesn't have to do with the IDE (possibly except for jupyter)

But to get what you want, you need to explicitly create two images and plot the heatmaps inside each one. By default, it seems that seaborn.heatmap uses only one figure and one axes.

import pandas as pd 
import seaborn as sn
import matplotlib.pyplot as plt

fig1, ax1 = plt.subplots()
fig2, ax2 = plt.subplots()

data = {'A': [45, 31, 42, 35, 39], 
        'B': [38, 31, 26, 28, 33], 
        'C': [10, 15, 17, 21, 12], 
        'D': [9, 14, 16, 22, 141]} 
df = pd.DataFrame(data, columns=['A', 'B'])
corrMatrix = df.corr()
sn.heatmap(corrMatrix, annot=True, ax=ax1)

df = pd.DataFrame(data, columns=['C', 'D'])
corrMatrix = df.corr()
sn.heatmap(corrMatrix, annot=True, ax=ax2)

plt.show()

If one figure with two axes is good enough for you, you can replace the two subplots with

fig, (ax1, ax2) = plt.subplots(ncols=2)
Related