0
votes

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?

1

1 Answers

0
votes

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.