46

I am using Spyder and plotting Seaborn countplots in a loop. The problem is that the plots seem to be happening on top of each other in the same object and I end up seeing only the last instance of the plot. How can I view each plot in my console one below the other?

for col in df.columns:
   if  ((df[col].dtype == np.float64) | (df[col].dtype == np.int64)):
       i=0
       #Later
   else :
       print(col +' count plot \n') 
       sns.countplot(x =col, data =df)
       sns.plt.title(col +' count plot')        
m00am
  • 5,910
  • 11
  • 53
  • 69
Tronald Dump
  • 1,300
  • 3
  • 16
  • 27
  • check this post here:https://stackoverflow.com/questions/55770326/matplotlib-loop-through-axes-in-a-seaborn-plot-for-multiple-subplots., you can simply loop over columns – Jia Gao Nov 19 '19 at 18:32

6 Answers6

42

You can create a new figure each loop or possibly plot on a different axis. Here is code that creates the new figure each loop. It also grabs the int and float columns more efficiently.

import matplotlib.pyplot as plt

df1 = df.select_dtypes([np.int, np.float])
for i, col in enumerate(df1.columns):
    plt.figure(i)
    sns.countplot(x=col, data=df1)
fpersyn
  • 1,045
  • 1
  • 12
  • 19
Ted Petrou
  • 59,042
  • 19
  • 131
  • 136
  • 2
    If i want to plot everything in one figure, instead of one below the other, how do i do that ? – Kshitij Yadav Oct 23 '18 at 16:19
  • 2
    ``` fig,ax = subplots(n,1, figsize=(6,12), sharex=True) for i in range(n): sca(ax[i]) sns.countplot(x=col, data=df1) ``` Change size of figure for ur needs. – sherdim Oct 24 '18 at 11:10
  • Why do you think it's more efficent? Don't you create a copy of dataframe `df` when selecting dtypes? OP's code doesn't do that – mhnatiuk Feb 18 '22 at 15:33
29

Before calling sns.countplot you need to create a new figure.

Assuming you have imported import matplotlib.pyplot as plt you can simply add plt.figure() right before sns.countplot(...)

For example:

import matplotlib
import matplotlib.pyplot as plt
import seaborn

for x in some_list:
    df = create_df_with(x)
    plt.figure() #this creates a new figure on which your plot will appear
    seaborn.countplot(use_df);
Jona
  • 1,023
  • 2
  • 15
  • 39
jorgeh
  • 1,727
  • 20
  • 32
7

To answer on the question in comments: How to plot everything in the single figure? I also show an alternative method to view plots in a console one below the other.

import matplotlib.pyplot as plt

df1 = df.select_dtypes([np.int, np.float])

n=len(df1.columns)
fig,ax = plt.subplots(n,1, figsize=(6,n*2), sharex=True)
for i in range(n):
    plt.sca(ax[i])
    col = df1.columns[i]
    sns.countplot(df1[col].values)
    ylabel(col);

Notes:

  • if a range of values in your columns differs - set sharex=False or remove it
  • no need for titles: seaborn automatically inserts column names as xlabel
  • for compact view change xlabels to ylabel as in the code snippet
Đorđe Relić
  • 418
  • 4
  • 13
sherdim
  • 1,159
  • 8
  • 19
0

You can add a plt.show() for each iteration as follows

for col in df.columns:
   if  ((df[col].dtype == np.float64) | (df[col].dtype == np.int64)):
       i=0
       #Later
   else :
       print(col +' count plot \n') 
       sns.countplot(x =col, data =df)
       sns.plt.title(col +' count plot')
       plt.show()   
0
plt.figure(figsize= (20,7))
for i,col in enumerate(signals.columns[:-1]):
 k = i +1
 plt.subplot(2,6,int(k))
 sns.distplot(x= signals[col], 
 color='darkblue',kde=False).set(title=f"{col}");
 plt.xlabel("")
 plt.ylabel("")
 #plt.grid()
plt.show()
Vignesh V
  • 1
  • 3
0
import seaborn as sns
import matplotlib.pyplot as plt




def print_heatmap(data):
    plt.figure()
    sns.heatmap(data)

for i in data. columns :
    print_heatmap(i)

jashia
  • 1
  • 1