matplotlibaxistwiny

Twiny() axis not aligned to lower axis


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

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.enter image description here 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()

and the results is shown in the figure

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.

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


Solution

  • 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)
    

    that problem will be solved.

    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')
    

    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.