Open In App

How to plot a dashed line in matplotlib?

Last Updated : 22 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Matplotlib is used to create visualizations and plotting dashed lines is used to enhance the style and readability of graphs. A dashed line can represent trends, relationships or boundaries in data. Below we will explore how to plot and customize dashed lines using Matplotlib. To plot dashed line:

Syntax: matplotlib.pyplot.plot(x, y, linestyle=’dashed’)

where:

  • x:  X-axis points on the line.
  • y:  Y-axis points on the line.
  • linestyle: Change the style of the line.

1. Plotting a dashed line in matplotlib

To plot the dashed line we will use a dataset and then use the above syntax. We can also use ‘–‘ while defining linestyle.

Python
import matplotlib.pyplot as plt

x_points = [1.5, 2.6, 3.5, 4, 9]
y_points = [3.25, 6.3, 4.23, 1.35, 3]

plt.plot(x_points, y_points, linestyle='dashed')
plt.show()

Output:

The above plot represent line chart with a dashed line connecting the points.

2. Customizing color of dashed line

You can change the color of the dashed line using the color parameter.

Syntax: plt.plot(linestyle=’–’, color=’gold’)

Python
import matplotlib.pyplot as plt

X = [1.5, 2.6, 3.5, 4, 9]
Y = [3.25, 6.3, 4.23, 1.35, 3]

plt.plot(X, Y, linestyle='dashed', color='gold')

plt.show()

Output:

3. Customizing width of dashed line

Use the linewidth parameter to control the thickness of the dashed line.

Syntax: plt.plot(linestyle=’dashed’, linewidth= int)

Python
import matplotlib.pyplot as plt

X = [1.5, 5.6, 3.5, 4, 9]
Y1 = [1, 4, 3, 4, 5]
Y2 = [6, 7, 4, 9, 10]

plt.plot(X, Y1, linestyle='dashed', color='black')
plt.plot(X, Y2, linestyle='dashed', 
         color='red', linewidth=4)

plt.show()

Output

Two dashed lines are created, one black with default width and another red with increased thickness.



Next Article
Article Tags :
Practice Tags :

Similar Reads