文本周围的边框有间隙

Mag*_*nus 4 python matplotlib

我想在 matplotlib 图中的一些文本周围添加边框,我可以使用patheffects.withStroke. 但是,对于某些字母和数字,符号的右上角有一个小间隙。

有没有什么办法可以不出现这个差距呢?

最小工作示例:

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")
Run Code Online (Sandbox Code Playgroud)

这给出了图像,显示了 S 和 6 个符号中的间隙。 在此输入图像描述

我正在使用 matplotlib 1.5.1。

Try*_*yph 5

文档没有提到它(或者我没有找到它),但是在代码中搜索,我们可以看到该patheffects.withStroke方法接受很多关键字参数。

您可以通过在交互式会话中执行以下命令来获取这些关键字参数的列表:

>>> 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']
Run Code Online (Sandbox Code Playgroud)

您正在寻找的参数capstyle接受 3 个可能的值:

  • “屁股”
  • “圆形的”
  • “投射”

在您的情况下,“round”值似乎可以解决问题。考虑下面的代码...

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")
Run Code Online (Sandbox Code Playgroud)

...它产生这个:

在此输入图像描述


接受的关键字参数实际上是GraphicsContextBaseset_*类的所有方法(减去“set_”前缀)。您可以在类文档中找到有关接受值的详细信息。