2016-03-15 42 views
0

我有以下条形图。使用matplotlib中的酒吧在轴顶部对齐xticks

enter image description here

我想上的曲线图的顶部上的x轴的xticks到与杆对准。

所以,与其间距[105, 20, 75, ...]均匀,我想让他们分开,使得105是第一栏上方,4是最后一棒上面,等

这将如何做呢?

实施例代码(上图,其生成):

from matplotlib import pyplot as plt 

x = [10, 20, 30, 40, 90] 
y = [7, 8, 12, 25, 50] 
other = [105, 20, 75, 20, 4] 

fig,ax = plt.subplots() 
plt.bar(x,y) 

ax.set_title('title', y=1.04) 
ax.set_xlabel('x label') 
ax.set_ylabel('y label') 

ax2 = ax.twiny() 
ax2.set_xticklabels(ax2.xaxis.get_majorticklabels(), rotation=90) 
ax2.set_xticklabels(other) 

plt.show() 

回答

1

你想要做什么,是手动指定使用ax2.set_xticks(locations)的XTICK位置。此外,您还要确保axax2的xlims相同。这保证了滴答会与酒吧排队。我们可以用set_xlimget_xlim来做到这一点。如果我们修改代码的ax2部分并考虑这些更改,我们会得到以下结果。

ax2 = ax.twiny() 

# Ensure that the x limits are the same 
ax2.set_xlim(ax.get_xlim()) 

# Set the labels to be the values we want and rotated 
ax2.set_xticklabels(other, rotation=90) 

# Place the xticks on ax2 at the bar centers 
ax2.set_xticks(x) 

enter image description here