Reputation: 91
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)
Upvotes: 4
Views: 7307
Reputation: 80299
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()
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()]
Upvotes: 4
Reputation: 1106
In your specific case you could just get the ticks of the figure and add 25 to them to shift them into the middle of the bars. You could also completely reset them.
ticks = plt.gca().get_xticks()
ticks += 25
plt.xticks(ticks)
Alternatively, if you plot a histogram with matplotlib, you can get the bins directly:
x = np.random.rand(100)
# Matplotlib only
counts, bins, patches = plt.hist(x)
plt.xticks(bins + 25)
Upvotes: 0