python - 文本周围的边框间隙

标签 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")

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

我正在使用 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")

...它产生这个:

enter image description here


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

关于python - 文本周围的边框间隙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39391592/

相关文章:

python - 'method' 对象在 python 中不可使用子脚本

Python: "TypeError: __str__ returned non-string"但仍打印输出?

python - 不规则间隔的热图

python - 在Python中忽略大于x分钟的时间间隔Matplotlib

python - 使用 Tensorflow-2.0 tf.optimizers 时如何修复 'The given object is not an Optimizer instance'?

python - 问题子类化 random.Random (python/CPython 2.6)

python - 使用多级索引重命名 pandas 中的列

python - 从 0 到 matplotlib 和 pandas 数据的值开始的 y 轴断开

python - 我如何告诉 OSX 使用brew 中的matplotlib,而不是默认的?

python - matplotlib中以空格作为千​​位分隔符的科学刻度数