matplotlib create broken axis in subplot

前端 未结 1 934
后悔当初
后悔当初 2021-01-16 09:22

I have a problematic subplot that has two scales of data. Instead of using a log scale, I want to break the axis, so that half of the subplot y axis runs from 0 to 10 and th

相关标签:
1条回答
  • 2021-01-16 09:54

    I might suggest to use only two subplots, one at the top and one at the bottom. Then, divide the upper one into two via mpl_toolkits.axes_grid1.make_axes_locatable.

    import numpy as np
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    
    
    x = np.random.uniform(0, 10, 40)
    y = np.concatenate([np.random.uniform(0, 1, 30), np.random.uniform(0, 100, 10)])
    y2 = np.random.uniform(0, 1, 40) 
    
    fig, axes = plt.subplots(nrows=2, sharex=True)
    
    ax = axes[0]
    divider = make_axes_locatable(ax)
    ax2 = divider.new_vertical(size="100%", pad=0.1)
    fig.add_axes(ax2)
    
    ax.scatter(x, y)
    ax.set_ylim(0, 1)
    ax.spines['top'].set_visible(False)
    ax2.scatter(x, y)
    ax2.set_ylim(10, 100)
    ax2.tick_params(bottom=False, labelbottom=False)
    ax2.spines['bottom'].set_visible(False)
    
    
    # From https://matplotlib.org/examples/pylab_examples/broken_axis.html
    d = .015  # how big to make the diagonal lines in axes coordinates
    # arguments to pass to plot, just so we don't keep repeating them
    kwargs = dict(transform=ax2.transAxes, color='k', clip_on=False)
    ax2.plot((-d, +d), (-d, +d), **kwargs)        # top-left diagonal
    ax2.plot((1 - d, 1 + d), (-d, +d), **kwargs)  # top-right diagonal
    
    kwargs.update(transform=ax.transAxes)  # switch to the bottom axes
    ax.plot((-d, +d), (1 - d, 1 + d), **kwargs)  # bottom-left diagonal
    ax.plot((1 - d, 1 + d), (1 - d, 1 + d), **kwargs)  # bottom-right diagonal
    
    
    #create bottom subplot as usual
    axes[1].scatter(x, y2)
    
    
    plt.show()
    

    0 讨论(0)
提交回复
热议问题