How to Plot a Matrix of Seaborn Distplots for All Columns in the Dataframe

Slightly more elegant imo than the solution by @Bruce Swain:

import matplotlib.pyplot as plt
import seaborn as sns

for i, column in enumerate(df.columns, 1):
    plt.subplot(3,3,i)
    sns.histplot(df[column])

You can create multiple figures with matplotlib using subplots like this

import matplotlib.pyplot as plt
# Define the number of rows and columns you want
n_rows=3
n_cols=3
# Create the subplots
fig, axes = plt.subplots(nrows=n_rows, ncols=n_cols)

You can view the subplots function as creating a matrix (2D array) of shape [n_rows, n_cols], and using the coordinates of elements of the matrix to choose where to plot.

You then plot each column in a different subplot with the ax argument to give the coordinates of an element of matrix. Using ax=axes[i,j] will specify the subplot you want to print in:

for i, column in enumerate(df.columns):
    sns.distplot(df[column],ax=axes[i//n_cols,i%n_cols])

From BenCaldwell comment "i//ncols gives the floor division which is the row when you are working left to right then top to bottom. i%ncols will give you the integer remainder which is the column when you are working left to right top to bottom."

If you want to plot a discrete dataset instead of using distplot to estimate the data distribution behind your data, you can use the new histplot function.


This should work:

fig, axes = plt.subplots(nrows = 3, ncols = 3)    # axes is 2d array (3x3)
axes = axes.flatten()         # Convert axes to 1d array of length 9
fig.set_size_inches(15, 15)

for ax, col in zip(axes, train.columns):
  sns.distplot(train[col], ax = ax)
  ax.set_title(col)