IanT
IanT

Reputation: 79

Seaborn: lining up 2 distplots on same axes

I'm trying to create 2 distplots that overlap on same axes, but they seem to be offset. How can I adjust this so that their overlapping is exact? Please see the image link below for the issue I have.

plt.figure(figsize=(10,8))
ax1 = sns.distplot(loans['fico'][loans['credit.policy']==1], bins= 10, kde=False, hist_kws=dict(edgecolor='k', lw=1))
ax2 = sns.distplot(loans['fico'][loans['credit.policy']==0], bins= 10, color='Red', kde=False, hist_kws=dict(edgecolor='k', lw=1))

ax1.set_xlim([600, 850])
ax2.set_xlim([600, 850])

Problematic result

Upvotes: 1

Views: 1659

Answers (1)

mostlyoxygen
mostlyoxygen

Reputation: 991

The plots aren't lining up because Seaborn (well, Matplotlib behind the scenes) is working out the best way to give you ten bins for each set of data you pass to it. But the two sets might not have the same range.

You can provide a sequence as the bins argument, which defines the edges of the bins. Assuming you have numpy available you can use its linspace function to easily create this sequence from the smallest and largest values in your data.

plt.figure(figsize(10,8))

bins = np.linspace(min(loans['fico']), max(loans['fico']), num=11)

ax1 = sns.distplot(loans['fico'][loans['credit.policy']==1], bins=bins, 
                   kde=False, hist_kws=dict(edgecolor='k', lw=1))
ax2 = sns.distplot(loans['fico'][loans['credit.policy']==0], bins=bins, 
                   color='Red', kde=False, hist_kws=dict(edgecolor='k', lw=1))

And then you shouldn't need to set the x limits.

An example with some randomly generated values: enter image description here

Upvotes: 4

Related Questions