Search code examples
pythonmatplotlibplotlinestyle

Set the space size of matplotlibs linestyle "dashed"


Is there any way to set the space size/thickness between consecutive dashes when plotting using the linestyle "dashed"? What I am looking for is to have the freedom to plot using the following linestyles:

-----
-  -  -  -
-     -     -    -

Included below is a short piece of code. I was thinking that this would be a matter of linestyle options. However, could not find it, nor in the archive of SO.

import numpy

x = numpy.linspace(0, 100, 101)
y = x

plt.plot(x, y, "r", linestyle = "dashed")
plt.show()

Solution

  • Line2D instance have the property dashes, which is a sequence of numbers. The first item is the length (in points) for the first on-segment, the second one for the off-segment, the third one on, and so on. The sequence is cycled over the entire length of the line.

    So (10,5) means: 10 points on-ink, 5 points off-ink, and so on...

    Here you go:

    import numpy as np
    import matplotlib.pyplot as plt
    
    x = np.linspace(0, 100, 101)
    y = x
    
    plt.plot(x, y, "r", linestyle = "dashed", dashes=(10,5)) # short gap
    plt.plot(x, y+5, "r", linestyle = "dashed", dashes=(10,20)) # long gap
    plt.plot(x, y+10, "r", linestyle = "dashed", dashes=(5,5,5,5,5,15,15,5,15,5,15,15,5,5,5,5,5,35)) # SOS
    plt.show()