Search code examples
matplotlibaxesmultiple-axes

Plot with 3 different x axis and the same y axis in matplotlib?


I've been trying to plot a figure that has 3 different x axis but the y axis is the same and it's the same, contiguous curve. The first part of the x axis goes up to a point (in the figure, that's zero). The second part of the axis is on a different scale (in the figure is shown on top). The 3rd section starts where the first section ended (zero, in this case). I wanted to plot the curve without any breaks. Could something like in the picture be done in matplotlib? Thank you in advance.

enter image description here


Solution

  • It is a bit unclear how the center part should look like, and which scaling that axis should have. But the general structure could be created as follows:

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, (ax1, ax2, ax3) = plt.subplots(ncols=3, sharey=True,
                                        gridspec_kw={'wspace': 0, 'width_ratios': [3, 2, 3]})
    for side in ('top', 'right'):
        ax1.spines[side].set_visible(False)
    ax2.spines['bottom'].set_visible(False)
    for side in ('left', 'right', 'top'):
        ax3.spines[side].set_visible(False)
    ax2.xaxis.tick_top()
    for side in ('left', 'right'):
        ax2.spines[side].set_linestyle((0, (4, 4)))
    ax2.set_zorder(2)  # to show the dashed axes
    ax2.tick_params(axis='y', left=False, right=False)
    ax3.tick_params(axis='y', left=False, right=False)
    
    ax1.set_xlim(-2.5, 0)
    ax2.set_xlim(-1, 1)
    ax3.set_xlim(0, 2.5)
    
    x = np.linspace(-2.5, 2.5, 500)
    y = np.sin(np.pi * x * np.abs(x))
    ax1.plot(x, y)
    ax2.plot(x, y)
    ax3.plot(x, y)
    plt.tight_layout()
    plt.show()
    

    example plot