Pandas DataFrame.hist Seaborn equivalent

Viewed 1409

When exploring a I often use Pandas' DataFrame.hist() method to quickly display a grid of histograms for every numeric column in the dataframe, for example:

import matplotlib.pyplot as plt
import pandas as pd
from sklearn import datasets


data = datasets.load_iris()
df = pd.DataFrame(data.data, columns=data.feature_names)

df.hist(bins=50, figsize=(10,7))
plt.show()

Which produces a figure with separate plots for each column: Which produces a figure with separate plots for each column

I've tried the following:

import pandas as pd
import seaborn as sns
from sklearn import datasets


data = datasets.load_iris()
df = pd.DataFrame(data.data, columns=data.feature_names)

for col_id in df.columns:
    sns.distplot(df[col_id])

But this produces a figure with a single plot and all columns overlayed: But this produces a figure with a single plot and all columns overlayed

Is there a way to produce a grid of histograms showing the data from a DataFrame's columns with Seaborn?

5 Answers

You can take advantage of seaborn's FacetGrid if you reorganize your dataframe using melt. Seaborn typically expects data organized this way (long format).

g = sns.FacetGrid(df.melt(), col='variable', col_wrap=2)
g.map(plt.hist, 'value')

enter image description here

There is no equivalent as seaborn displot itself will only pick 1-D array, or list, maybe you can try generating the subplots.

fig, ax = plt.subplots(2, 2, figsize=(10, 10))

for i in range(ax.shape[0]):
    for j in range(ax.shape[1]):
        sns.distplot(df[df.columns[i*2+j]], ax=ax[i][j])

enter image description here

Anothert useful SEABORN method to quickly display a grid of histograms for every numeric column in the dataframe for you could be the quick,clean and handy sns.pairplot()

try: sns.pairplot(df) this has a lot of cool parameters you can explor like Hue etc

pairplot example for iris dataset

if you DON'T want the scatters you can actually create a customised grid really really quickly using sns.PairGrid(df) this creates an empty grid with all the spaces and you can map whatever you want on them :g = sns.pairgrid(df)

`g.map(sns.distplot)` or `g.map_diag(plt.scatter)`

etc

I ended up adapting jcaliz's to make it work more generally, i.e. not just when the DataFrame has four columns, I also added code to remove any unused axes and ensure axes appear in alphabetical order (as with df.hist()).

size = int(math.ceil(len(df.columns)**0.5))
fig, ax = plt.subplots(size, size, figsize=(10, 10))

for i in range(ax.shape[0]):
    for j in range(ax.shape[1]):
        data_index = i*ax.shape[1]+j
        if data_index < len(df.columns):
            sns.distplot(df[df.columns.sort_values()[data_index]], ax=ax[i][j])

for i in range(len(df.columns), size ** 2):
    fig.delaxes(ax[i // size][i % size])
Related