Side-specific padding for matplotlib text bbox(matplotlib 文本 bbox 的侧边特定填充)
问题描述
在 matplotlib 中添加文本时,是否可以在 bbox 的特定一侧指定填充?我正在添加一个 LaTex 表格作为文本,由于某种原因,表格自然未对齐,没有填充规范.我想说明这一点,以便在 bbox 顶部添加填充.
Is it possible to specify the padding on a specific side of the bbox when adding text in matplotlib? I'm adding a LaTex table as text and for some reason the table is misaligned naturally with no padding specifications. I'd like to account for this for adding padding on the top of the bbox.
不幸的是,似乎没有向 bbox 的特定侧添加填充的选项.这可能吗?
Unfortunately, there doesn't seem to be an option for adding padding to a specific side of a bbox. Is this possible?
这里有一个例子来说明:
Here's an example to illustrate:
import matplotlib
matplotlib.rc('text',usetex=True)
import matplotlib.pyplot as plt
import numpy as np
text = '\begin{tabular}{|c|c|}\hline 1 & 2 \\ \hline 3 & 4 \\ \hline \end{tabular}'
plt.imshow(np.zeros((10,10)), cmap=plt.cm.gray)
plt.text( 4.5,
4.5,
text,
fontsize=24,
bbox=dict(fc='w',boxstyle='square,pad=0.5'), va='center', ha='center')
plt.axis('off')
plt.show()
推荐答案
我找到了一个基于建议的答案的解决方法在这篇文章中.一个更简单的解决方案也将不胜感激.我还应该说,垂直错位似乎只有在我设置 usetex: True 时才会发生.
I've found a workaround which is based on the answer suggested in this post. An easier solution would also be appreciated. I should also say that the vertical misalignment seems to happen only when I set usetex: True.
这是上面的修改版本:
import matplotlib
matplotlib.rc('text',usetex=True)
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np
text = '\begin{tabular}{|c|c|}\hline1&2\\\hline3&4\\\hline\end{tabular}'
fig, ax = plt.subplots(1)
img = ax.imshow(np.zeros((10,10)), cmap=plt.cm.gray)
txt = ax.text( 4.5,
4.5,
text,
fontsize=24,
ha='center',
va='center',
bbox=dict(alpha=0))
fig.canvas.draw()
bbox = txt.get_bbox_patch()
xmin = bbox.get_window_extent().xmin
xmax = bbox.get_window_extent().xmax
ymin = bbox.get_window_extent().ymin
ymax = bbox.get_window_extent().ymax
xmin, ymin = fig.transFigure.inverted().transform((xmin, ymin))
xmax, ymax = fig.transFigure.inverted().transform((xmax, ymax))
dx = xmax-xmin
dy = ymax-ymin
# The bounding box vals can be tweaked manually here.
rect = Rectangle((xmin-0.02,ymin-0.01), dx+0.04, dy+0.05, fc='w', transform=fig.transFigure)
ax.add_patch(rect)
fig.canvas.draw()
ax.axis('off')
plt.savefig('ok.png',bbox_inches='tight')
这会产生:
这篇关于matplotlib 文本 bbox 的侧边特定填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:matplotlib 文本 bbox 的侧边特定填充
基础教程推荐
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
