0

I'm trying to plot a graph that has two x-axes on matplotlib. However, it's not behaving how I would expect it to

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax1 = fig.add_subplot(111)
x = np.linspace(-10,10,1000)
y = np.sin(x*np.pi/2)
ax1.plot(x,y)

ax2 = ax1.twiny()
tick_locations = ax1.get_xticks() - 5.
tick_labels = ax1.get_xticks()

ax2.set_xticks(tick_locations[1:])
ax2.set_xticklabels(tick_labels[1:])

plt.show()

gives:

enter image description here

Shouldn't the ax2 labels read: [ -5. 0. 5. 10.] at ax1 locations [-10. -5. 0. 5.]

Any ideas why it's stretching them out?

Ben
  • 6,986
  • 6
  • 44
  • 71

1 Answers1

0

edit your code:

ax2.set_xticks(tick_locations[:])
ax2.set_xticklabels(tick_labels[1:])

edit: "Based Carla gama's response to this post it seems you should be able to select any tick locations?"

note that there is a ax2.set_xlim in his code, so you can also do this:

ax2.set_xlim(tick_locations[0], tick_locations[-1])
ax2.set_xticks(tick_locations[1:]) #1, not 0
ax2.set_xticklabels(tick_labels[1:])

I think the key is you should let your ax2 xlim same range as ax1.

Community
  • 1
  • 1
zhangxaochen
  • 32,744
  • 15
  • 77
  • 108
  • Based Carla gama's response to [this post](http://stackoverflow.com/questions/10514315/how-to-add-a-second-x-axis-in-matplotlib) it seems you should be able to select any tick locations? – Ben Jan 10 '14 at 05:27
  • It looks like `set_xlim` needs to come after `set_xticks`. Other wise `set_xticks` redefines the limits. But you're right, that was the problem. – Ben Jan 10 '14 at 19:41