0
0
MatplotlibHow-ToBeginner ยท 3 min read

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.

  • linewidth or its short form lw accepts 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 linewidth inside the plotting function.
  • Confusing linewidth with size or 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

ParameterDescriptionExample
linewidth or lwSets the thickness of the lineplt.plot(x, y, linewidth=2)
Default valueDefault line width if not set1.0
Value typeNumeric (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.