Search code examples
pythonmatplotlibaxis-labels

twiny() in matplotlib changes the y-axis scale


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

And after: enter image description here

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

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


Solution

  • 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():

    enter image description here

    and with ax2 = ax1.twiny():

    enter image description here

    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!