Changing plot scale by a factor in matplotlib

后端 未结 3 1274
半阙折子戏
半阙折子戏 2020-11-27 15:44

I am creating a plot in python. Is there a way to re-scale the axis by a factor? The yscale and xscale commands only allow me to turn log scale off

3条回答
  •  清酒与你
    2020-11-27 16:01

    As you have noticed, xscale and yscale does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so:

    ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
    ax.xaxis.set_major_formatter(ticks)
    

    A complete example showing both x and y scaling:

    import numpy as np
    import pylab as plt
    import matplotlib.ticker as ticker
    
    # Generate data
    x = np.linspace(0, 1e-9)
    y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude
    
    # setup figures
    fig = plt.figure()
    ax1 = fig.add_subplot(121)
    ax2 = fig.add_subplot(122)
    # plot two identical plots
    ax1.plot(x, y)
    ax2.plot(x, y)
    
    # Change only ax2
    scale_x = 1e-9
    scale_y = 1e3
    ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
    ax2.xaxis.set_major_formatter(ticks_x)
    
    ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
    ax2.yaxis.set_major_formatter(ticks_y)
    
    ax1.set_xlabel("meters")
    ax1.set_ylabel('volt')
    ax2.set_xlabel("nanometers")
    ax2.set_ylabel('kilovolt')
    
    plt.show() 
    

    And finally I have the credits for a picture:

    Note that, if you have text.usetex: true as I have, you may want to enclose the labels in $, like so: '${0:g}$'.

提交回复
热议问题