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')
In Seaborn, we will plot multiple graphs in a single window in two ways. First with the help of Facetgrid() function and other by implicit with the help of matplotlib. data: Tidy dataframe where each column is a variable and each row is an observation.
As we have used the groupby function to show the barplot multiple columns. Just specify the three parameters x, y, and hue to generate the bar plot in multiple columns. So, let's begin with adding the python modules for plotting the multiple bars of the plot.
You can use the following basic syntax to create subplots in the seaborn data visualization library in Python: #define dimensions of subplots (rows, columns) fig, axes = plt. subplots(2, 2) #create chart in each subplot sns. boxplot(data=df, x='team', y='points', ax=axes[0,0]) sns.
Seaborn is more comfortable in handling Pandas data frames. It uses basic sets of methods to provide beautiful graphics in python. Matplotlib works efficiently with data frames and arrays.It treats figures and axes as objects. It contains various stateful APIs for plotting.
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)
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);
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With