matplotliblineoverlapping

How can I exclude overlapping shapes to make a dashed line always visible against a solid overlap?


I am trying to recreate the dashed line effect seen in the attached image using matplotlib.

enter image description here

I could not find any reference


Solution

  • To do this you need Matplotlib v3.6.0 or higher, in which the (currently experimental) gapcolor option was added for dashed lines. You can see an example here, and I'll show an example below:

    from matplotlib import pyplot as plt
    import numpy as np
    
    d = np.random.randn(30)
    plt.plot(d, "g", lw=10)
    
    # overplot a dashed line with gapcolor set to white
    # (in your example image the linestyle is ":" rather than "--", so choose what you like)
    plt.axhline(0, color="g", ls="--", gapcolor="white")
    

    This gives:

    enter image description here

    If you don't have the latest Matplotlib version, or can't upgrade, you can get the effect by just plotting a white line and then a dashed line over the top (or vice versa), e.g.,

    plt.plot(d, "g", lw=10)
    
    # plot a white line
    plt.axhline(0, color="white")
    
    # overplot a dashed green line
    plt.axhline(0, color="g", ls="--"")