How to plot a dashed line in matplotlib ?

Published: July 25, 2019

DMCA.com Protection Status

Examples of how to plot dashed lines in matplotlib:

Plot a dashed line

To plot a dashed line a solution is to add '--'' ':' or '-:', example:

import matplotlib.pyplot as plt

x = [1,10]
y = [3,6]

plt.plot(x,y,'--')

plt.savefig('DashedLine_01.png')
plt.show()

How to plot a dashed line in matplotlib using '--'
How to plot a dashed line in matplotlib using '--'

import matplotlib.pyplot as plt

x = [1,10]
y = [3,6]

plt.plot(x,y,':')

plt.savefig('DashedLine_02.png')
plt.show()

How to plot a dashed line in matplotlib using  ':''
How to plot a dashed line in matplotlib using ':''

import matplotlib.pyplot as plt

x = [1,10]
y = [3,6]

plt.plot(x,y,'-.')

plt.savefig('DashedLine_03.png')
plt.show()

How to plot a dashed line in matplotlib using '-.
How to plot a dashed line in matplotlib using '-.

Custom dashed line

It is also possible to create a custom dashed line see:

import matplotlib.pyplot as plt

x = [1,10]
y = [3,6]

dashes = [5,2,10,5] # 5 points on, 2 off, 3 on, 1 off

l, = plt.plot(x,y, '--')

l.set_dashes(dashes)

plt.title('How to plot a dashed line in matplotlib ?', fontsize=7)

plt.savefig("dashed_line.png", bbox_inches='tight')

plt.show()

Custom dashed line with matplotlib
Custom dashed line with matplotlib

References

Image

of