gpt4 book ai didi

python matplotlib : How can I place text in a given area?

转载 作者:行者123 更新时间:2023-12-05 07:06:20 24 4
gpt4 key购买 nike

在 matplotlib 图形中放置文本时,可以在轴坐标中指定位置。但是,随着文本变长,它最终会占用更多空间。按照建议here ,给定一个文本,可以在其周围绘制一个边界框。有没有办法反过来做,也就是说,给定一个用户定义的边界框,确保文本保留在该边界框中?我知道这可能需要自动调整字体大小或换行。我只是不确定 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()

Resulting plot

最佳答案

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

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

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

表示屏幕上文本的最大长度为 50 像素。如您所见,这不是一个太复杂的解决方案,方法名称以下划线开头,这表明这并不是真的要在公共(public) 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()

结果是: fig

关于 python matplotlib : How can I place text in a given area?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62553623/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com