0

I have the below code. In a nutshell, I need to duplicate the bottom x axes so I keep already plotted data (in place) but change the xlim. I have tried set_xlim after plotting the data (just readjusts the data to the new scale (as expected); also tried to duplicate the axis (with twiny) and then customise with a new scale (and then add lines with axvline). The below way works, however, the label is now not sticking with the axes! I thought I must be missing something.

Any suggestions?

import matplotlib.pyplot as plt


plt.plot([1,2,1,4,5],[1,2,3,4,5], marker='o', label='value 1')
plt.plot([3,1,3,1,2],[1,2,3,4,5], label='value 2')

plt.gca().get_xaxis().set_visible(False)

ax1 = plt.twiny()
ax2 = ax1.twiny()


ax1.set_xlabel('TOP')
ax2.set_xlabel('BOTTOM')

plt.savefig(fname='test.png')

plt.show()

Labels not in correct place!

It's very much like this question (Changing axis without changing data (Python)), but I use a constant (say 0 to 750) as the original plot and the range I want to set the xlim to is somewhat unrelated to the original data (say 0 to 30000).

geekscrap
  • 965
  • 2
  • 12
  • 26

1 Answers1

2

Both, ax1 and ax2 are twin axes. Those have their label up. (This may be unexpected, and may be seen as a bug, indeed.)

When working with several axes, it is cumbersome to use pyplot directly. Instead the object oriented approach is much better suited to make sure you set the properties of the object you want to be using.

The idea is then to set the label position manually set_label_position to the bottom.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1,2,1,4,5],[1,2,3,4,5], marker='o', label='value 1')
ax.plot([3,1,3,1,2],[1,2,3,4,5], label='value 2')

ax.get_xaxis().set_visible(False)

ax1 = ax.twiny()
ax2 = ax1.twiny()
ax2.xaxis.set_label_position('bottom') 

ax1.set_xlabel('TOP', labelpad=20)
ax2.set_xlabel('BOTTOM', labelpad=20)

plt.show()

enter image description here

Also some labelpad needs to be set (again for no specific reason, other than probably noone every though about the implications of creating a twin axes from a twin axes).

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • This works (thanks!) but I'm still slightly confused (however, as you say, this may be a bug), add "ax2.set_visible(False)" before plt.show().... The wrong axis disappears...! Am I going crazy?! – geekscrap Jul 19 '18 at 23:29
  • Yes, that's what I mean by "noone every though about the implications of creating a twin axes from a twin axes". Note that in a future version of matplotlib there will be a [`secondary_xaxis` available](https://github.com/matplotlib/matplotlib/pull/11589) for exactly such purposes, such that one does not have to misuse `twinx` which was never designed for something like this. – ImportanceOfBeingErnest Jul 19 '18 at 23:36
  • Ahha, brilliant. Thanks – geekscrap Jul 20 '18 at 06:19