3

在 matplotlib 图形中放置文本时,可以在轴坐标中指定位置。但是,随着文本变长,最终会占用更多空间。正如这里所建议的,给定一个文本,可以在它周围绘制一个边界框。有没有办法反过来做,也就是说,给定一个用户定义的边界框,确保文本留在那个边界框中?我知道这可能需要自动调整字体大小或换行。我只是不确定 matplotlib 中是否已经存在这样的东西。

用例:我想要得到一个由矩形单元格组成的表格,如下所示,其中每个单元格都应包含一个小字符串。字符串不应离开单元格并相互重叠。最佳情况下,应该输入它们。这是生成表格的代码(到目前为止没有文字)。如果您能想出一种更简单的方法来实现我的目标,而不是在 matplotlib 中处理文本,请也告诉我。

import matplotlib.pyplot as plt
import numpy as np
import sys

np.random.seed(int(sys.argv[1]))

fig, ax = plt.subplots(1,1)
all_coordinates = np.array([(i,j) for i in range(1, 6) for j in range(1,6)])
for i, coordinates in enumerate(np.random.permutation(all_coordinates)):
    x, y = coordinates
    if i<9:
        color = 'r'
    elif i<17:
        color = 'b'
    elif i<24:
        color = 'y'
    else:
        color = 'k'
    ax.fill_between(np.arange(x-0.5, x+0.5, 0.01), y-0.5, y+0.5, color=color)
low, high = 0.5, 5.5
ax.set_xlim(low, high)
ax.set_ylim(low, high)

major_ticks = np.arange(1, 6, 1)
ax.set_xticks(major_ticks)
ax.set_yticks(major_ticks)

minor_ticks = [1.5, 2.5, 3.5, 4.5]
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(minor_ticks, minor=True)
ax.grid(True, which='minor')
plt.show()

结果图

4

1 回答 1

0

好吧,这个答案并不完整,但我认为它应该足以让你开始。我不会关心需要调整文本大小的太长字符串。(为什么会有人想写一部关于情节的小说?)

Matplotlib 指定时默认使用图形框wrap=True。您需要覆盖它以返回您的盒子大小:

t = ax.text(x, y, 'text', ha='center', va='center', wrap=True)
t._get_wrap_line_width = lambda : 50

这意味着屏幕上文本的最大长度为 50 像素。正如您所看到的,这不是一个过于复杂的解决方案,方法名称以下划线开头,这表明这并不是真的要在公共 API 中使用。

我完成了你的例子:

import matplotlib.pyplot as plt
import numpy as np

text = 'this is a long-long string'

fig, ax = plt.subplots(1,1)
all_coordinates = np.array([(i,j) for i in range(1, 6) for j in range(1,6)])

for i, coordinates in enumerate(np.random.permutation(all_coordinates)):
    x, y = coordinates
    if i<9:
        color = 'r'
    elif i<17:
        color = 'b'
    elif i<24:
        color = 'y'
    else:
        color = 'k'
    ax.fill_between(np.arange(x-0.5, x+0.5, 0.01), y-0.5, y+0.5, color=color)

    txt = ax.text(x, y, text, ha='center', va='center', wrap=True)
    txt._get_wrap_line_width = lambda : 50

low, high = 0.5, 5.5
ax.set_xlim(low, high)
ax.set_ylim(low, high)

major_ticks = np.arange(1, 6, 1)
ax.set_xticks(major_ticks)
ax.set_yticks(major_ticks)

minor_ticks = [1.5, 2.5, 3.5, 4.5]
ax.set_xticks(minor_ticks, minor=True)
ax.set_yticks(minor_ticks, minor=True)
ax.grid(True, which='minor')
plt.show()

这导致: 图

于 2020-06-24T11:41:31.937 回答