Aligning ticks of primary and secondary x-axes

68 Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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.

3
On

I'm not able to replicate the same graph as your img, but if IIUC you need to manually set the xticks for both the primary and secondary axes as otherwise they are automatically set leading to some difference. Just use set_xticks something like below to align the ticks:

ax1.set_xticks(np.linspace(0, ax1.get_xbound()[1]+1, 5))
ax2.set_xticks(np.linspace(0, ax2.get_xbound()[1]+1, 5))

Output:

enter image description here