python - matplotlib 文本 bbox 的特定边距

标签 python matplotlib latex

在 matplotlib 中添加文本时,是否可以在 bbox 的特定一侧指定填充?我正在添加一个 LaTex 表作为文本,由于某种原因,该表自然未对齐,没有填充规范。我想考虑到在 bbox 顶部添加填充。

不幸的是,似乎没有将填充添加到 bbox 特定侧的选项。这可能吗?

这里有一个例子来说明:

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()

最佳答案

我找到了一种基于 the answer suggested in this post 的解决方法.一个更简单的解决方案也将不胜感激。我还应该说,垂直错位似乎只有在我设置 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')

这产生:

关于python - matplotlib 文本 bbox 的特定边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35249489/

相关文章:

emacs - 一键 Emacs LaTeX 编译?

python - 如何为 python http 连接指定经过身份验证的代理?

python - 删除字符串的第一个字符

python - 在Python中以列表形式读取数据?

python - 一行散点图标签 - Matplotlib

python - 带有圆圈表示人口规模的热图

Python unicode编码问题

python - scipy 插值从文件导入的二维数据

latex - 如何以 UTF8 编译 LaTeX?

latex - 在 Rstudio 中合并 rmarkdown 生成的 latex 文档,而无需手动删除序言