Twiny()轴未与下轴对齐-matplotlib

Twiny()轴未与下轴对齐-matplotlib,matplotlib,axes,Matplotlib,Axes,我希望你能帮我解决这个小问题 我正在绘制三组errorbars数组,我希望在绘图的顶部有第二组记号。因此,我创建了一个新的双轴,我给它提供了相同的刻度坐标,x。应该执行此操作的代码部分如下 x = np.arange(len(Stars))*2 fig = plt.figure() ax1 = fig.add_subplot(111) ax2 = ax1.twiny() ax1.errorbar(x-.5,[Jmin_IS[i] for i in Ind],yerr=[[J1sL_IS[i]

我希望你能帮我解决这个小问题

我正在绘制三组errorbars数组,我希望在绘图的顶部有第二组记号。因此,我创建了一个新的双轴,我给它提供了相同的刻度坐标,
x
。应该执行此操作的代码部分如下

x = np.arange(len(Stars))*2
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

ax1.errorbar(x-.5,[Jmin_IS[i] for i in Ind],yerr=[[J1sL_IS[i] for i in Ind],[J1sR_IS[i] for i in Ind]],fmt='o',ms=6)
ax1.errorbar(x   ,[Jmin_OM[i] for i in Ind],yerr=[[J1sL_OM[i] for i in Ind],[J1sR_OM[i] for i in Ind]],fmt='s',ms=6)
ax1.errorbar(x+.5,[Jmin_CA[i] for i in Ind],yerr=[[J1sL_CA[i] for i in Ind],[J1sR_CA[i] for i in Ind]],fmt='^',ms=6)
for xv in np.arange(len(Stars))*4: ax1.axvspan(xv-1, xv+1, color='grey',alpha=.5)
x2labels = [str(r'N$_{\star}$=%i'%Stars[i]) for i in Ind]
ax1.set_xticks(x)
ax2.set_xticks(x)
ax2.set_xticklabels(x2labels, rotation=90)    
ax1.set_ylim(15,21)
ax1.set_xlim(-1,39)
plt.tight_layout()
plt.grid(ls='dotted',axis='y')
plt.show()
结果如图所示

存在两个问题:首先,双轴ax2刻度移动(N_星号与底部x轴的刻度不对齐),并且y方向上没有显示网格


有人能发现错误吗?这是python包版本的问题吗?非常感谢

顶部y轴和底部y轴的刻度不对齐的问题是因为您更改了第一个轴的x数据限制。换一种方式,您更改了一个轴的“x-zoom”,但没有更改另一个轴的“x-zoom”,这会导致刻度错位。 如果你也写

ax2.set_xlim(-1,39)
这个问题将得到解决

至于没有出现y形网格线,可以使用第一个轴的
网格
方法解决:

ax1.grid(ls='dotted',axis='y')
当您调用
plt.grid
(或
pyplot
中的任何其他方法)时,它将在最后一个激活轴上运行,在本例中为
ax2
。我不太清楚为什么
ax2.grid(axis='y')
不显示网格线,但在作为另一个轴基础的轴上使用该方法是一个简单的解决方案