pythonmatplotlibplot

matplotlib zoomed in x-axis at beginning and end


i have a signal with a relativly high frequency and i want to have a detailed look at the start of the recorded signal and the end. Like the signal is 1 hour long and i want the first 10 seconds and the last 10 seconds kind of zoomed in (on the x-axis) and the middle section "normal". I allready found this method 'axs.set_yscale('function', functions=(forward, inverse))' which should be able to define a custom scale, but i'm unable to understand how this works and i can not find a lot of documentation on this method.

I can not share the real data, but the data looks very similar to a sinus, so one can use this plot to visualize it:

fig, axs = plt.subplots()
x = np.arange(0, 1000 * np.pi, 0.1)
y = 2 * np.sin(x) + 3
axs.plot(x, y)

Solution

  • I think this is basically what you want. This maps 0-10 to 0-10, 10 to 30 pi to 10 to 20, and 30pi-10 to 1000 pi from 20 to 30 (eg 1/3 each). It includes extra values one either side in case your data extends beyond the limits you have specified.

    (Edit I only went to 30 pi because the plot was just a blue splotch if you went to 1000 pi, but its the same idea)

    import matplotlib.pyplot as plt
    import numpy as np
    
    fig, axs = plt.subplots()
    x = np.arange(0, 30 * np.pi, 0.1)
    y = 2 * np.sin(x) + 3
    axs.plot(x, y)
    
    xdata = np.array([-1e6, 0, 10, np.max(x) - 10, np.max(x), 1e6])
    # make 0 to 10 linear, 10 to max(x)-10 much faster linear
    # max(x)-10 to max(x) slower linear
    xnew = np.array([-1e6, 0, 10, 20, 30, 1e6])
    
    
    def forward(x):
        return np.interp(x, xdata, xnew)
    
    
    def inverse(x):
        return np.interp(x, xnew, xdata)
    
    axs.set_xscale('function', functions=(forward, inverse))
    

    Image with the first and last 10 s zoomed