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")
Author by
Alex L
Software Engineer in Perth, Australia with a passion for robotics, software, electronics and the web.
Updated on June 15, 2022Comments
-
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)
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 about 7 yearsThanks 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 asplt.hist
doing it automatically. I've updated my notebook: gist.github.com/alexlouden/42b5983f5106ec92c092f8a2697847e6 -
mwaskom about 7 yearsYou have not correctly adapted the example that I gave you. If you look, you will see that the
FacetGrid
does not havehue
, which is instead handled by themultihist
function. -
Alex L about 7 yearsOh sorry, my mistake. Thanks, this will work! I wish there was a way to do this within Seaborn a bit more elegantly