【问题标题】:matplotlib: histogram and bin labelsmatplotlib:直方图和 bin 标签
【发布时间】:2013-04-03 01:02:01
【问题描述】:

我正在尝试使用条形图绘制直方图,但我很难弄清楚如何将 x 轴标签与实际的 bin 对齐。下面的代码生成如下图:

如您所见,每个 x-label 的末尾未与其 bin 的中心对齐。我正在考虑的方式是:当我应用 45 度旋转时,标签围绕其几何中心旋转。我想知道是否可以将枢轴移动到标签的顶部。 (或者简单地将所有标签稍微向左平移。)

import matplotlib.pyplot as plt
import numpy as np

#data
np.random.seed(42)
data = np.random.rand(5)
names = ['A:GBC_1233','C:WERT_423','A:LYD_342','B:SFS_23','D:KDE_2342']

ax = plt.subplot(111)
width=0.3
bins = map(lambda x: x-width/2,range(1,len(data)+1))
ax.bar(bins,data,width=width)
ax.set_xticks(map(lambda x: x, range(1,len(data)+1)))
ax.set_xticklabels(names,rotation=45)

plt.show()

【问题讨论】:

    标签: rotation matplotlib histogram bar-chart axis-labels


    【解决方案1】:

    用途:

    ax.set_xticklabels(names,rotation=45, rotation_mode="anchor", ha="right")
    

    输出是:

    【讨论】: