简体   繁体   English

如何在 seaborn distplot 的 bin 中心标记 xticks?

[英]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.我想 plot 使用 seaborn 和 xticks 在箱的中点的 distplot。 I am using the below code:我正在使用以下代码:

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

这就是我的显示当前的样子

To get the midpoints of the bars, you can extract the generated rectangle patches and add half their width to their x position.要获取条形的中点,您可以提取生成的矩形补丁并将其宽度的一半添加到它们的 x position。 Setting these midpoints as xticks will label the bars.将这些中点设置为 xticks 将 label 条形。

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:如果您需要 bin 边缘而不是它们的中心:

edges = [rect.get_x() for rect in ax.patches] + [ax.patches[-1].get_x() + ax.patches[-1].get_width()]

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.在您的特定情况下,您可以只获取图形的刻度并向它们添加 25 以将它们移动到条形的中间。 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:或者,如果您使用 plot 使用 matplotlib 的直方图,则可以直接获取 bin:

x = np.random.rand(100)

# Matplotlib only
counts, bins, patches = plt.hist(x)
plt.xticks(bins + 25)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM