Second matplotlib x-axis related to the first one : wrong tick position
<p>I would like to add a second x-axis to a matplotlib plot, not to add a second plot, but to add labels linked to the first axis. The answers in this <a href="https://stackoverflow.com/questions/10514315/how-to-add-a-second-x-axis-in-matplotlib">question</a> somehow fail to adress a problem in the bounds of the second axis :</p>

<p>The following code plot the log10 of the first x-axis as a second axis :</p>

<pre><code>import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(3,figsize = [5,4])
ax1 = fig.add_subplot(111)
ax1.set_xlabel('first axis')
ax1.set_xlim([0, 120])
ax1.grid(True)

ax2 = ax1.twiny()
ax2.set_xlim(ax1.get_xlim())
# or alternatively :
# ax2.set_xbound(ax1.get_xbound())
second_ticks = np.array([1.,10.,100.])
ax2.set_xticks(second_ticks)
ax2.set_xticklabels(np.log10(second_ticks))
ax2.set_xlabel('second axis')

plt.show()
</code></pre>

<p><a href="https://i.stack.imgur.com/FQAYe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FQAYe.png" alt="enter image description here"></a></p>

<p>It works ! 
Now let's change <code>ax1.set_xlim([0, 120])</code> by <code>ax1.set_xlim([20, 120])</code></p>

<p><a href="https://i.stack.imgur.com/uIWgV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uIWgV.png" alt="enter image description here"></a></p>

<p>Now it fails. I tried with <code>ax2.set_xbound(ax1.get_xbound())</code> with no differences. Somehow <code>ax2.set_xticks</code> fails to place the ticks according to the right x limits. </p>

<p>EDIT :</p>

<p>I tried to place <code>ax1.set_xlim([20, 120])</code> anywhere after <code>ax2.set_xlim(ax1.get_xlim())</code> it gives again the wrong things :</p>

<p><a href="https://i.stack.imgur.com/UedJL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UedJL.png" alt="enter image description here"></a></p>

<p>Actually i don't get the meaning of <code>ax2.set_xticks()</code>, It sets position where ticklabels will be displayed no ? </p>

<p>EDIT :</p>

<p><strong>Ok, we got it : the x_lim definition <code>ax2.set_xlim(ax1.get_xlim())</code> must come after the tick and ticklabel definition.</strong></p>

<pre><code>import numpy as np
import matplotlib.pyplot as plt

plt.close('all')

fig = plt.figure(1,figsize = [5,4])
ax1 = fig.add_subplot(111)
ax1.set_xlabel('first axis')
ax1.grid(True)
ax1.set_xlim([10, 120])

ax2 = ax1.twiny()

second_ticks = np.array([1.,10.,100.])
ax2.set_xticks(second_ticks)
ax2.set_xticklabels(np.log10(second_ticks))
ax2.set_xlabel('second axis')
ax2.set_xlim(ax1.get_xlim())

fig.tight_layout()

plt.show()
</code></pre>

<p><a href="https://i.stack.imgur.com/J7Lmk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J7Lmk.png" alt="enter image description here"></a></p>

<p>Thanks !</p>

<p>Regards,</p>