我想在 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")
我正在使用 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)。您可以在类文档中找到有关可接受值的详细信息。
关于python - 文本周围的边框间隙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39391592/