Skip to main content
 首页 » 编程设计

python之文本周围的边框间隙

2024年10月17日7三少

我想在 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") 

这给出了图像,它显示了 S 和 6 个符号中的间隙。

我正在使用 matplotlib 1.5.1。

请您参考如下方法:

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

您可以通过在交互式 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'] 

您要查找的参数是 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") 

...它产生这个:


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