Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mark xticks at the center of bins for a seaborn distplot?

I want to plot a distplot using seaborn with xticks at the mid point of the bins. I am using the below code:

sns.distplot(df['MILEAGE'], kde=False, bins=20)

This is what my displot currently looks like

like image 855
dododips Avatar asked Oct 25 '25 20:10

dododips


1 Answers

To get the midpoints of the bars, you can extract the generated rectangle patches and add half their width to their x position. Setting these midpoints as xticks will label the bars.

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

ax = sns.distplot(np.random.randn(1000).cumsum(), kde=False, bins=20)
mids = [rect.get_x() + rect.get_width() / 2 for rect in ax.patches]
ax.set_xticks(mids)
plt.show()

example plot

If the tick labels would overlap too much, you could rotate them and/or adapt their fontsize:

ax.tick_params(axis='x', rotation=90, labelsize=8)

If you need the bin edges instead of their centers:

edges = [rect.get_x() for rect in ax.patches] + [ax.patches[-1].get_x() + ax.patches[-1].get_width()]
like image 114
JohanC Avatar answered Oct 27 '25 10:10

JohanC