0
0
MatplotlibHow-ToBeginner ยท 3 min read

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.pyplot as plt.
  • Overriding linestyle by specifying style or 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:

LinestyleDescriptionExample
'-'Solid lineplt.plot(x, y, linestyle='-')
'--'Dashed lineplt.plot(x, y, linestyle='--')
'-.'Dash-dot lineplt.plot(x, y, linestyle='-.')
':'Dotted lineplt.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.