How to Set Line Width in Matplotlib: Simple Guide
To set the line width in Matplotlib, use the
linewidth or lw parameter in plotting functions like plt.plot(). For example, plt.plot(x, y, linewidth=2) draws a line with width 2.Syntax
The linewidth parameter controls the thickness of lines in Matplotlib plots. It can be used in most plotting functions like plt.plot(), ax.plot(), and others.
linewidthor its short formlwaccepts a numeric value representing the line thickness.- Higher values mean thicker lines.
- Default line width is usually 1.0.
python
plt.plot(x, y, linewidth=2) # or plt.plot(x, y, lw=2)
Example
This example shows how to plot two lines with different widths using Matplotlib. The first line has the default width, and the second line is thicker with linewidth=4.
python
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y1 = [1, 4, 9, 16, 25] y2 = [25, 16, 9, 4, 1] plt.plot(x, y1, label='Default width') plt.plot(x, y2, linewidth=4, label='Thick line') plt.legend() plt.title('Line Width Example') plt.show()
Output
A plot window showing two lines: one thin line and one thick line with label 'Thick line'.
Common Pitfalls
Common mistakes when setting line width include:
- Using a string instead of a number for
linewidth, which causes errors. - Forgetting to pass
linewidthinside the plotting function. - Confusing
linewidthwithsizeor other unrelated parameters.
Always use a numeric value and place linewidth as a keyword argument in the plot call.
python
import matplotlib.pyplot as plt x = [1, 2, 3] y = [1, 4, 9] # Wrong: linewidth as string (causes error) # plt.plot(x, y, linewidth='thick') # Correct: plt.plot(x, y, linewidth=3) plt.show()
Output
A plot with a line thicker than default, no errors.
Quick Reference
| Parameter | Description | Example |
|---|---|---|
| linewidth or lw | Sets the thickness of the line | plt.plot(x, y, linewidth=2) |
| Default value | Default line width if not set | 1.0 |
| Value type | Numeric (int or float) | 2, 3.5, etc. |
Key Takeaways
Use the linewidth or lw parameter to control line thickness in Matplotlib plots.
Pass a numeric value to linewidth; higher means thicker lines.
Set linewidth inside the plotting function call like plt.plot(x, y, linewidth=2).
Avoid using strings or incorrect parameter names for line width.
Default line width is 1.0 if you do not specify linewidth.