0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Set Line Style in Matplotlib: Simple Guide

In Matplotlib, you set the line style using the linestyle parameter in plotting functions like plot(). You can use styles like '-' for solid, '--' for dashed, ':' for dotted, or '-.' for dash-dot lines.
๐Ÿ“

Syntax

The linestyle parameter controls the style of the line in Matplotlib plots. It accepts strings that define the pattern of the line.

  • '-': solid line (default)
  • '--': dashed line
  • ':': dotted line
  • '-.': dash-dot line

You use it inside plotting functions like plt.plot(x, y, linestyle='--').

python
import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [2, 3, 5]

plt.plot(x, y, linestyle='--')  # Dashed line
plt.show()
Output
A plot with a dashed line connecting points (1,2), (2,3), and (3,5).
๐Ÿ’ป

Example

This example shows how to plot multiple lines with different line styles using the linestyle parameter.

python
import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4]
y1 = [0, 1, 4, 9, 16]
y2 = [0, 1, 2, 3, 4]
y3 = [0, 1, 0, 1, 0]

plt.plot(x, y1, linestyle='-')   # Solid line
plt.plot(x, y2, linestyle='--')  # Dashed line
plt.plot(x, y3, linestyle=':')   # Dotted line
plt.title('Different Line Styles in Matplotlib')
plt.show()
Output
A plot with three lines: solid, dashed, and dotted, each showing different data.
โš ๏ธ

Common Pitfalls

Common mistakes when setting line styles include:

  • Using incorrect strings like 'dash' instead of '--'.
  • Forgetting to use the linestyle keyword argument.
  • Confusing linestyle with style or ls (though ls is a valid shortcut).

Always use one of the accepted strings or the shortcut aliases.

python
import matplotlib.pyplot as plt

x = [1, 2, 3]
y = [3, 2, 1]

# Wrong way (won't change line style):
plt.plot(x, y, linestyle='dash')  # Incorrect string
plt.title('Wrong linestyle example')
plt.show()

# Right way:
plt.plot(x, y, linestyle='--')  # Correct dashed line
plt.title('Correct linestyle example')
plt.show()
Output
First plot shows a solid line because 'dash' is invalid; second plot shows a dashed line as expected.
๐Ÿ“Š

Quick Reference

Line StyleString CodeDescription
Solid'-'Continuous solid line
Dashed'--'Line with dashes
Dotted':'Line with dots
Dash-dot'-.'Line with dash-dot pattern
None'' or 'None'No line drawn
โœ…

Key Takeaways

Use the linestyle parameter in plotting functions to set line styles in Matplotlib.
Common line styles include '-', '--', ':', and '-.'.
Use correct string codes; invalid strings default to solid lines.
You can also use the shortcut 'ls' instead of 'linestyle'.
Line style helps make plots clearer and visually distinct.