30

I try:

points = [...]
axe.plot([i[0] for i in points], [i[1] for i in points], linestyle='-', linewidth=10, 
color='black', markeredgewidth=2, markeredgecolor='green')

But I just get a black contour. How can I achieve something like on the following picture? black line with green border

Alex
  • 1,204
  • 4
  • 14
  • 26

3 Answers3

80

If you plot a line twice it won't show up in the legend. It's indeed better to use patheffects. Here are two simple examples:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.patheffects as pe

# setup data
x = np.arange(0.0, 1.0, 0.01)
y = np.sin(2*2*np.pi*t)

# create line plot including an outline (stroke) using path_effects
plt.plot(x, y, color='k', lw=2, path_effects=[pe.Stroke(linewidth=5, foreground='g'), pe.Normal()])
# custom plot settings
plt.grid(True)
plt.ylim((-2, 2))
plt.legend(['sine'])
plt.show()

enter image description here

Or if you want to add a line shadow

# create line plot including an simple line shadow using path_effects
plt.plot(x, y, color='k', lw=2, path_effects=[pe.SimpleLineShadow(shadow_color='g'), pe.Normal()])
# custom plot settings
plt.grid(True)
plt.ylim((-2, 2))
plt.legend(['sine'])
plt.show()

enter image description here

Mattijn
  • 12,975
  • 15
  • 45
  • 68
  • Thank you for pointing to the path_effects. This even works with collections. Like this: t = ax.add_collection(lines) t.set_path_effects([path_effects.PathPatchEffect(offset=(1,-1), facecolor='gray'), path_effects.PathPatchEffect(edgecolor='white', linewidth=1.1, facecolor='black')]) – Mikhail Lisakov May 27 '19 at 11:17
  • Thank you for the example @Mattijn. I tried to add borders to a dashed line but it does not work at the gaps. Do you know of a workaround? – Stefano Nov 07 '19 at 17:05
  • Beautiful! It even works on text. – Ted Tinker Dec 28 '21 at 05:13
10

Just plot the line twice with different thicknesses:

axe.plot([i[0] for i in points], [i[1] for i in points], linestyle='-', linewidth=10, 
color='green')
axe.plot([i[0] for i in points], [i[1] for i in points], linestyle='-', linewidth=5, 
color='black')
aganders3
  • 5,838
  • 26
  • 30
5

The more general answer is to use patheffects. Easy outlines and shadows (and other things) for any artist rendered with a path.
The matplotlib docs (and examples) are quite accessible.

http://matplotlib.org/users/patheffects_guide.html

http://matplotlib.org/examples/pylab_examples/patheffect_demo.html

travc
  • 1,788
  • 1
  • 18
  • 9