How to Create Dashed Line in Matplotlib: Simple Guide
To create a dashed line in
matplotlib, use the linestyle='--' parameter in the plotting function like plt.plot(). This tells Matplotlib to draw the line with dashes instead of solid lines.Syntax
Use the linestyle parameter in plotting functions to set the line style. Common values are:
'-': solid line'--': dashed line'-.': dash-dot line':': dotted line
Example syntax:
plt.plot(x, y, linestyle='--')
python
plt.plot(x, y, linestyle='--')Example
This example shows how to plot a simple dashed line using matplotlib. It plots a line with x values from 0 to 4 and y values as their squares, using a dashed line style.
python
import matplotlib.pyplot as plt x = [0, 1, 2, 3, 4] y = [0, 1, 4, 9, 16] plt.plot(x, y, linestyle='--', color='blue', marker='o') plt.title('Dashed Line Example') plt.xlabel('x') plt.ylabel('y') plt.grid(True) plt.show()
Output
A plot window showing a blue dashed line connecting points (0,0), (1,1), (2,4), (3,9), (4,16) with circle markers and grid lines.
Common Pitfalls
Common mistakes when creating dashed lines include:
- Using
linestyle='dash'instead of'--'. The correct value for dashed lines is'--'. - Not importing
matplotlib.pyplotasplt. - Overriding
linestyleby specifyingstyleor other conflicting parameters.
Example of wrong and right usage:
python
import matplotlib.pyplot as plt x = [0, 1, 2] y = [0, 1, 4] # Wrong: linestyle value incorrect # plt.plot(x, y, linestyle='dash') # This will cause an error or default to solid # Right: plt.plot(x, y, linestyle='--') plt.show()
Output
A plot window showing a dashed line connecting points (0,0), (1,1), (2,4).
Quick Reference
Here is a quick reference for common linestyle values in Matplotlib:
| Linestyle | Description | Example |
|---|---|---|
| '-' | Solid line | plt.plot(x, y, linestyle='-') |
| '--' | Dashed line | plt.plot(x, y, linestyle='--') |
| '-.' | Dash-dot line | plt.plot(x, y, linestyle='-.') |
| ':' | Dotted line | plt.plot(x, y, linestyle=':') |
Key Takeaways
Use linestyle='--' in plt.plot() to create dashed lines in Matplotlib.
Common linestyle options include '-', '--', '-.', and ':'.
Avoid incorrect linestyle values like 'dash' which cause errors or default styles.
Combine linestyle with color and marker for clearer plots.
Always import matplotlib.pyplot as plt before plotting.