Can I give a border to a line in Matplotlib plot function?

To give a border to a line in Matplotlib plot function, you can call plot() twice with different line widths. The first plot creates a wider border line, and the second plot creates a narrower main line on top.

Basic Approach

The technique involves plotting the same data twice ?

  • First plot with wider line width for the border
  • Second plot with narrower line width for the main line
  • The wider line shows through as a border around the narrower line

Example

Here's how to create a red line with a black border ?

import numpy as np
import matplotlib.pyplot as plt

# Set figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create data points
x = np.linspace(-2, 2, 100)
y = np.sin(x)

# Plot border (wider, black line)
plt.plot(x, y, c='black', lw=10, label='Border')

# Plot main line (narrower, red line)
plt.plot(x, y, c='red', lw=8, label='Main line')

plt.title('Line with Border Effect')
plt.xlabel('X values')
plt.ylabel('Y values')
plt.show()

Output

X values Y values Line with Border Effect -2 -1 0 1 2 1 0 -1

Customizing Border Colors

You can experiment with different border and main line colors ?

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-2, 2, 100)
y = np.sin(x)

# Blue line with white border
plt.plot(x, y, c='white', lw=12)
plt.plot(x, y, c='blue', lw=8)

plt.title('Blue Line with White Border')
plt.show()

Key Points

  • Border line width should be larger than the main line width
  • The difference in line widths determines the border thickness
  • Both plots must use the same data points for proper alignment
  • The border line is plotted first, then the main line on top

Conclusion

Creating bordered lines in Matplotlib is achieved by plotting the same data twice with different line widths. This technique gives you full control over border color and thickness for enhanced visual effects.

Updated on: 2026-03-25T21:16:41+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements