Histogram bin size in seaborn

13,284

You'll need to define a wrapper function for plt.hist that does the hue grouping itself, something like

%matplotlib inline

import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")
tips.loc[tips.time == "Lunch", "total_bill"] *= 2

def multihist(x, hue, n_bins=10, color=None, **kws):
    bins = np.linspace(x.min(), x.max(), n_bins)
    for _, x_i in x.groupby(hue):
        plt.hist(x_i, bins, **kws)

g = sns.FacetGrid(tips, row="time", sharex=False)
g.map(multihist, "total_bill", "smoker", alpha=.5, edgecolor="w")

enter image description here

Share:
13,284
Alex L
Author by

Alex L

Software Engineer in Perth, Australia with a passion for robotics, software, electronics and the web.

Updated on June 15, 2022

Comments

  • Alex L
    Alex L almost 2 years

    I'm using Seaborn's FacetGrid to plot some histograms, and I think the automatic bin sizing uses just the data of each category (rather than each subplot), which leads to some weird results (see skinny green bins in y = 2):

    g = sns.FacetGrid(df, row='y', hue='category', size=3, aspect=2, sharex='none')
    _ = g.map(plt.hist, 'x', alpha=0.6)
    

    Seaborn histogram

    Is there a way (using Seaborn, not falling back to matplotlib) to make the histogram bin sizes equal for each plot?

    I know I can specify all the bin widths manually, but that forces all the histograms to be the same x range (see notebook).

    Notebook: https://gist.github.com/alexlouden/42b5983f5106ec92c092f8a2697847e6

  • Alex L
    Alex L about 7 years
    Thanks for the answer! I've been having a play with this, and it looks like multihist is called once per hue per histogram - so setting the bins manually inside the function actually ends up with the same result as plt.hist doing it automatically. I've updated my notebook: gist.github.com/alexlouden/42b5983f5106ec92c092f8a2697847e6
  • mwaskom
    mwaskom about 7 years
    You have not correctly adapted the example that I gave you. If you look, you will see that the FacetGrid does not have hue, which is instead handled by the multihist function.
  • Alex L
    Alex L about 7 years
    Oh sorry, my mistake. Thanks, this will work! I wish there was a way to do this within Seaborn a bit more elegantly