2013-04-10 103 views
8

我想绘制直方图与条形图,我很难搞清楚如何对齐x轴标签与实际的箱子。下面的代码会生成以下图表:Bar chartmatplotlib:直方图和bin标签

正如您所看到的,每个x标签的末尾并未与其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() 

回答

9

用途:

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

输出是:

enter image description here

+0

辉煌,谢谢大家! – dimka 2013-04-11 15:33:33