combining a log and linear scale in matplotlib

后端 未结 3 490
时光说笑
时光说笑 2020-12-05 21:01

The example here What is the difference between 'log' and 'symlog'? nicely shows how a linear scale at the origin can be used with a log scale elsewhere. I

3条回答
  •  暖寄归人
    2020-12-05 21:31

    This solution makes an addition to cphlewis's answer so that there is a smooth transition, and the plot appears to have consistent tick markers. My change adds these three lines:

    axLin.spines['bottom'].set_visible(False)

    axLin.xaxis.set_ticks_position('top')

    plt.setp(axLin.get_xticklabels(), visible=False)

    In total, the code is

    # linear and log axes for the same plot?
    # starting with the histogram example from 
    # http://matplotlib.org/mpl_toolkits/axes_grid/users/overview.html
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    import numpy as np
    
    # Numbers from -50 to 50, with 0.1 as step
    xdomain = np.arange(-50,50, 0.1)
    
    axMain = plt.subplot(111)
    axMain.plot(xdomain, np.sin(xdomain))
    axMain.set_yscale('log')
    axMain.set_ylim((0.01, 0.5))
    axMain.spines['top'].set_visible(False)
    axMain.xaxis.set_ticks_position('bottom')
    
    divider = make_axes_locatable(axMain)
    axLin = divider.append_axes("top", size=2.0, pad=0, sharex=axMain)
    axLin.plot(xdomain, np.sin(xdomain))
    axLin.set_xscale('linear')
    axLin.set_ylim((0.5, 1.5))
    
    # Removes bottom axis line
    axLin.spines['bottom'].set_visible(False)
    axLin.xaxis.set_ticks_position('top')
    plt.setp(axLin.get_xticklabels(), visible=False)
    
    plt.title('Linear above, log below')
    
    plt.show()
    

提交回复
热议问题