python - 如何在 seaborn distplot 的 bin 中心标记 xticks?
问题描述
我想使用 seaborn 在 bin 的中点绘制带有 xticks 的 distplot。我正在使用以下代码:
sns.distplot(df['MILEAGE'], kde=False, bins=20)
解决方案
要获取条形的中点,您可以提取生成的矩形补丁并将其宽度的一半添加到它们的 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()]
推荐阅读
- api - 如何使用axios发送数据到line notify
- c# - 是否可以将 JsonAttribute 转换为 Integer
- python - xgboost predict_proba :如何在概率和标签之间进行映射
- php - 从 wp_list_pages() 中排除单个页面?
- python - Sys.getsizeof 在 IronPython 上返回一个常量值
- hibernate - 如何使用休眠连接两个表?
- java - 如何将字节字符串转换为字符串?
- apache-kafka - 移动端和网页端直接连接kafka是否可行
- c++ - 如何将字符串转换为 ASCII 值的总和?
- python - 通过网状在R中创建python列表