twiny() in matplotlib changes the y-axis scale

2019-06-14 12:08发布

问题:

Plotting some data with matplotlib, it happens that inserting the ax.twiny() module changes the scale of the y axis. Before I use it:

And after:

I would like to avoid to insert manually the limits in the y-axis.

So why does this happen, and how to fix it?

回答1:

That's weird.

I've tried using the twiny() option and it does not change the scale:

import numpy
import matplotlib.pylab as plt

x = numpy.linspace(0, 4. * numpy.pi, 1000)
y = numpy.cos(x)

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.plot(x, y)
ax2 = ax1.twiny()

This gives without ax2 = ax1.twiny():

and with ax2 = ax1.twiny():

Is this also the way you implement the second x-axis?

Using ax2 you will be able to plot new data using the shared y-axis and the second x-axis.

Hope this helps!



回答2:

I have this issue too. Not sure what causes it. This is a more robust fix

ax2.set_xlim(ax.get_xlim())