pythonmatplotlibplotlinestyle

can I make a custom linestyle in matplotlib for plot made up of multiple parallel lines


I am making a plot where I want to delineate two geological sections. To delineate I want to use three parallel dashed lines. I do not know how to make a multiline line in matplotlib. I made three sets of arrays that I offset. It looks okay but it is tedious to program and in some plots lines up really poorly. I din't know if there was a custom linestyle that was made up of multiple lines.

Pd=np.array([17.5,22.5,27.5,27.5,42.5,47.5,47.5,52.5,52.5,37.5,32.5,47.5,32.5,0,22.5,0])
Px=np.array([23.6685,23.681,23.6935,23.706,23.7185,23.731,23.7435,23.756,23.7685,23.781,23.7935,23.806,23.8185,23.831,23.8435,23.856])
Pd1=np.array([23.5,28.5,28.5,43.5,49.5,49.5,54.5,54.5,38.5,34.5,49.5,32.5,3,25.5,0])
Px1=np.array([23.681,23.6919,23.7044,23.7169,23.7294,23.7419,23.7544,23.7701,23.7826,23.7935,23.806,23.8201,23.831,23.8435,23.8576])
Pd2=np.array([21.5,26.5,26.5,41.5,45.5,45.5,50.5,50.5,35.5,29.5,45.5,32.5,-3,19.5,0])
Px2=np.array([23.681,23.6951,23.7076,23.7201,23.7326,23.7451,23.7576,23.7669,23.7794,23.7935,23.806,23.8169,23.831,23.8435,23.8544])

fig,ax=plt.subplots()
fig.set_size_inches(8,5)
ax.plot(Px,Pd,linestyle=(0,(10,5)),color='dimgray')#),linewidth=4)
ax.plot(Px1,Pd1,linestyle=(0,(10,5)),color='dimgray')#),linewidth=4)
ax.plot(Px2,Pd2,linestyle=(0,(10,5)),color='dimgray')#),linewidth=4)
ax.xaxis.set_ticks_position('top') 
ax.set_ylim(150,0)
ax.set_xlim(23.88,23.7125)
ax.set_xlabel(u'Latitude \N{DEGREE SIGN}N',fontsize=fs)
ax.xaxis.set_label_position('top')
ax.set_ylabel('Depth (m)')

enter image description here

I tried to make individual arrays but I didn't know if there was a better solution


Solution

  • You can use the Stroke path effects to re-draw the same line with a certain offset:

    import matplotlib.pyplot as plt
    import matplotlib.patheffects as path_effects
    
    Px = [23.6685,23.681,23.6935,23.706,23.7185,23.731,23.7435,23.756,23.7685,23.781,23.7935,23.806,23.8185,23.831,23.8435,23.856]
    Pd = [17.5,22.5,27.5,27.5,42.5,47.5,47.5,52.5,52.5,37.5,32.5,47.5,32.5,0,22.5,0]
    
    fig, ax = plt.subplots(figsize=(8, 5))
    ax.set_ylim(150,0)
    ax.set_xlim(23.88,23.7125)
    
    
    y_offset = 5   # offset in points
    ax.plot(Px, Pd, linestyle=(0, (10, 5)), color='dimgray',
           path_effects=[path_effects.Stroke(offset=(0, -y_offset)), 
                         path_effects.Normal(),
                         path_effects.Stroke(offset=(0, y_offset))])
    

    enter image description here