Marine graphics in a loop

I use Spyder and plot the 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 to view each story in the console below?

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')        
+7
source share
3 answers

You can create a new shape every cycle, or perhaps a graph on a different axis. Here is the code that creates a new drawing for each loop. It also captures int and float columns more efficiently.

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

for i, col in enumerate(df1.columns):
    plt.figure(i)
    sns.countplot(x=col, data=df1)
+10
source

Before calling sns.countplotyou need to create a new digit.

, import matplotlib.pyplot as plt, plt.figure() sns.countplot(...)

:

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);
+7

Answer the question in the comments: How to draw everything in one shape? I also show an alternative method for viewing graphs in the 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 the range of values ​​in your columns is different - set sharex = False or delete it
  • no headers needed: seaborn automatically inserts column names as xlabel
  • for compact presentation, change xlabels to ylabel, as in the code snippet
+2
source

Source: https://habr.com/ru/post/1664871/


All Articles