Magnus Magnus - 2 months ago 7
Python Question

Gaps in border around text

I would like to add a border around some texts in a matplotlib plot, which I can do using

patheffects.withStroke
. However, for some letters and number there is a small gap to the top right of the symbol.

Is there a way to not have this gap?

Minimal working example:

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

fig, ax = plt.subplots()
ax.text(
0.1, 0.5, "test: S6",
color='white',
fontsize=90,
path_effects=[patheffects.withStroke(linewidth=13, foreground='black')])
fig.savefig("text_stroke.png")


This gives the image, which shows the gap in S and 6 symbols.
enter image description here

I'm using matplotlib 1.5.1.

Answer

The documentation does not mention it (or I did not found it) but, searching in the code, we can see that the patheffects.withStroke method accepts a lot of keyword arguments.

You can have the list of those keyword arguments by executing this in interactive session:

>>> from matplotlib.backend_bases import GraphicsContextBase as gcb
>>> print([attr[4:] for attr in dir(gcb) if attr.startswith("set_")])
['alpha', 'antialiased', 'capstyle', 'clip_path', 'clip_rectangle', 'dashes', 'foreground', 'gid', 'graylevel', 'hatch', 'joinstyle', 'linestyle', 'linewidth', 'sketch_params', 'snap', 'url']

The argument you are looking for is capstyle which accepts 3 possible values:

  • "butt"
  • "round"
  • "projecting"

In you case, the "round" value seems to fix the problem. Consider the code below...

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

fig, ax = plt.subplots()
ax.text(
    0.1, 0.5, "test: S6",
    color='white',
    fontsize=90,
    path_effects=[patheffects.withStroke(linewidth=13, foreground='black', capstyle="round")])
fig.savefig("text_stroke.png")

... it produces this:

enter image description here


The accepted keywords arguments are actually all the set_* (minus the "set_" prefixe) methods of the GraphicsContextBase class. You can find details on the accepted values into the class documentation.

Comments