Twiny()轴未与下轴对齐-Matplotlib [英] Twiny() axis not aligned to lower axis - matplotlib

查看:85
本文介绍了Twiny()轴未与下轴对齐-Matplotlib的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I was hoping you could help me fixing this small issue.

我正在绘制三组误差线数组,我想在图的顶部绘制第二组刻度.因此,我创建了一个新的双轴,为刻度线提供了相同的坐标 x . 应该做的部分代码这是以下

I'm plotting three sets of errorbars arrays and I want to have a second set of ticks on the top part of the plot. So I create a new, twin axis to which I give the same coordinates for the ticks, x. The part of code which is supposed to do this is the following

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 方向的网格.

There are two problems: first the twin axis ax2 ticks are shifted (the N_star numbers are misaligned with respected to the ticks of the bottom x axis) and no grid in the y direction is displayed.

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

Can anybody spot a mistake? Is it a matter of python packages version? Thanks a lot

推荐答案

顶部 y 轴和底部 y 轴的刻度不对齐的问题是因为您更改了 x-datalimits第一个轴.换句话说,你改变了一个轴的x-zoom",但没有改变另一个轴的x-zoom",这会导致刻度线错位.如果你也写

The issue where the ticks of the top y-axis and the bottom y-axis don't align, is because you've changed the x-datalimits of the first axes. Put in a different way, you've changed the "x-zoom" of one axes, but not the "x-zoom" of the other which causes the ticks to misalign. If you also write

ax2.set_xlim(-1,39)

该问题将得到解决.

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

As for not having the y-gridlines appearing, that can be solved by using the grid method of the first axes:

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

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

When you call plt.grid (or any other method from pyplot) it will operate on the last active axes, which in this case is ax2. I'm not exactly sure why ax2.grid(axis='y') doesn't show the gridlines, but it's an easy solution to just use the method on the axes that served as the base for the other.

这篇关于Twiny()轴未与下轴对齐-Matplotlib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆