1

I am working on adding stroke around lines in matplotlib using matplotlib.patheffects. I have been trying out the solution mentioned in these two answers [1] and [2].

I have a question regarding adding stroke to butt-capped line in matplotlib.

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

outline = pe.withStroke(linewidth=8, foreground='black')

plt.figure(figsize=(8, 6))
plt.plot([1,2], [1,1], lw=5, color='red', path_effects=[outline], solid_capstyle="butt",
         label="stroke no alpha")

plt.plot([1,2], [2,2], lw=5, alpha=0.5, color='red', path_effects=[outline], solid_capstyle="butt",
         label="stroke with alpha")

plt.plot([1,2], [3,3], lw=5, alpha=0.5, color='red', solid_capstyle="butt",
         label="no stroke with alpha")

plt.legend(bbox_to_anchor=(1, 1.02), loc='upper left')
plt.show()

This is the resulting figure: enter image description here

If you look closer to the end of the lines, you can find that there are actually no borders (the stroke effect has the same length as the original line).

While for the projecting-capped line (default for line), the stroke effect works perfectly with border all around the line.

I also tried to pass the capstyle="projecting" in the withStroke call, but the resulting figure has thicker borders at both ends of the line.

output2

May I know is the any ways to achieve border for butt-capped line using withStroke? Or this is not achievable? I can think of a silly solution, which is to just plot a tiny vertical line at both ends of the line so as to complete the border. But is there other more elegant ways to do this?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Yichao Cai
  • 11
  • 2

0 Answers0