Search code examples
pythonmatplotlibaxis-labels

Matplotlib dual x-axis logarithmic ticks


I've set the upper x-axis manually (the conversion is 1.218x the values on the lower x-axis) and I'd like the upper minor logarithmic ticks to move up the scale by 1.218x too. Any suggestions?

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twiny()

X = np.linspace(0,10000000, 1000000)

ax1.semilogx(X, zero, label='$\mathbb{P} (X=0)$')
ax1.semilogx(X, one, label='$\mathbb{P} (X=1)$')
ax1.semilogx(X, two+more, label='$\mathbb{P} (X\geq2)$')
ax1.set_xlabel(r"Particle Concentration m$^{-3}$")
ax1.set_ylabel(r"Probability of occurrence")
ax1.legend(loc=6)
ax1.grid()

ax2.semilogx(X, one, label='one', alpha = 0)
ax2.set_xlim(ax1.get_xlim())
ax2.set_xticks([12.18323586744639, 121.8323586744639, 1218.323586744639, 12183.23586744639, 121832.3586744639, 1218323.586744639])
ax2.set_xticklabels(['10$^1$','10$^2$','10$^3$','10$^4$','10$^5$','10$^6$'])
ax2.set_xlabel(r"Disdrometer Particle Count (min$^{-1}$)")

plt.show()

Poisson pmf for raindrops inside an instrument


Solution

  • EDIT: Rewriting after your comment below.

    There will be a way to move the minor ticks but actually I think your approach here is misguided. Looking close you aren't using ax2 to plot anything: you just want it as an alternative scale. You are messing with the ticks and ticklabels when as a way of faking changing the limits. It would be much easier to just change that limits (so that matplotlib can handle the ticks etc automatically).

    Replace your code above with

    ax2.set_xscale("log", nonposx='clip')
    ax2.set_xlim(np.array(ax1.get_xlim())/1.218)