【问题标题】:Twiny() axis not aligned to lower axis - matplotlibTwiny() 轴未与下轴对齐 - matplotlib
【发布时间】:2016-05-24 15:41:47
【问题描述】:

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

我正在绘制三组误差线数组,我想在图的顶部有第二组刻度。所以我创建了一个新的双轴,我为刻度提供相同的坐标,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_star 数字相对于底部 x 轴的刻度未对齐)并且 y 方向没有显示网格。

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

【问题讨论】:

    标签: matplotlib axes


    【解决方案1】:

    顶部 y 轴和底部 y 轴的刻度不对齐的问题是因为您更改了第一个轴的 x-datalimits。换一种说法,你改变了一个轴的“x-zoom”,但没有改变另一个轴的“x-zoom”,这会导致刻度不对齐。 如果你也写

    ax2.set_xlim(-1,39)
    

    这个问题会解决的。

    至于没有出现y-gridlines,可以使用第一轴的grid方法解决:

    ax1.grid(ls='dotted',axis='y')
    

    当您调用 plt.grid(或来自 pyplot 的任何其他方法)时,它将在最后一个活动轴上运行,在本例中为 ax2。我不完全确定为什么ax2.grid(axis='y') 不显示网格线,但这是一个简单的解决方案,只需在作为另一个基础的轴上使用该方法。

    【讨论】:

      猜你喜欢
      • 2019-04-26
      • 2015-07-19
      • 1970-01-01
      • 2018-06-19
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多