首页 > 解决方案 > 如何在 seaborn distplot 的 bin 中心标记 xticks?

问题描述

我想使用 seaborn 在 bin 的中点绘制带有 xticks 的 distplot。我正在使用以下代码:

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

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

标签: pythonseabornxticks

解决方案


要获取条形的中点,您可以提取生成的矩形补丁并将其宽度的一半添加到它们的 x 位置。将这些中点设置为 xticks 将标记条形。

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()

示例图

如果刻度标签重叠太多,您可以旋转它们和/或调整它们的字体大小:

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

如果您需要 bin 边缘而不是它们的中心:

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

推荐阅读