pythonmatplotlibhistogramtwiny

Aligning ticks of primary and secondary x-axes


I am trying to align the ticks of the primary and secondary x-axes in my plot. The values in my absolute_mags and masses arrays should be equivalent, but are not lining up properly. The offset in the secondary axis is on the right, but it should be on the left to align with the ticks on the primary axis.

Currently, my code is as follows:

absolute_mags = np.array([4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14.5])
masses = 10 ** (np.array([0.058, -0.039, -0.136, -0.233, -0.333, -0.463, -0.637, -0.778, -0.867, -0.964, -1.11]))
masses = np.around(masses, 2)

plt.hist(absolute_RP_mags, bins='auto', linewidth=2, hatch='/', edgecolor='k', facecolor='None')
plt.ylabel("number of targets")
plt.xlabel("absolute G_RP magnitude (mag)")

ax1 = plt.gca()
ax1.set_xticks(ticks=absolute_mags,labels=absolute_mags)
ax2 = ax1.twiny()
ax2.set_xticks(ticks=absolute_mags, labels=masses)
ax2.set_xlabel("mass ($M/M_\odot$)")

This code produces the following plot:

enter image description here

How can I align ticks on the primary and secondary axes?

absolute_RP_mags can be approximated as a Gaussian with mu=9.86406767115786 and sigma=1.7088087089866282.


Solution

  • I found an answer that works for me!

    Adding ax2.set_xlim(ax1.get_xlim()) put the tick marks in the correct location on the secondary axis. If you didn't plot data on the secondary axis, it didn't have any data to align, so you need to draw the axis limits from the primary axis.