在带有 matplotlib 的 python 中:在缩小时消失的矩形内创建文本

问题描述 投票:0回答:1

我想使用 matplotlib 创建一个矩形,其中包含甘特图的文本。但如果放大和缩小,文本永远不应该大于矩形。因此,一旦文本(具有固定字体大小)大于矩形,它就应该消失,并且当它再次变小时(放大),它应该再次出现。

这是一个简单文本的示例,其问题是文本在缩放时不会停留在矩形内(不会在变大后立即消失)。

from matplotlib import pyplot as plt, patches
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot(111)
rectangle = patches.Rectangle((0, 0), 3, 3, edgecolor='orange',
facecolor="green", linewidth=7)
ax.add_patch(rectangle)
rx, ry = rectangle.get_xy()
cx = rx + rectangle.get_width()/2.0
cy = ry + rectangle.get_height()/2.0
ax.annotate("Rectangle", (cx, cy), color='black', weight='bold', fontsize=10, ha='center', va='center')
plt.xlim([-5, 5])
plt.ylim([-5, 5])
plt.show()

Text should disappear now

python matplotlib text rectangles
1个回答
0
投票

要监视绘图的缩放状态,您可以连接到

Axes
类的“xlim_changed”和“ylim_changed”事件。下面,我调整了你的代码,以便

  • 一旦绘图的 x/y 限制超过预设限制距离的两倍(即超过 10),文本就会被隐藏;
  • 一旦限制小于预设限制距离的两倍,文本就会再次显示。

这可能还不完美,但我希望它能让您了解如何继续。

from matplotlib import pyplot as plt, patches
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot(111)
rectangle = patches.Rectangle((0, 0), 3, 3, edgecolor='orange',
facecolor="green", linewidth=7)
ax.add_patch(rectangle)
rx, ry = rectangle.get_xy()
cx = rx + rectangle.get_width()/2.0
cy = ry + rectangle.get_height()/2.0
ann = ax.annotate("Rectangle", (cx, cy), color='black', weight='bold', fontsize=10, ha='center', va='center')

def on_lims_change(event):
    x_low, x_up = event.get_xlim()
    y_low, y_up = event.get_ylim()
    visible = (x_up - x_low) <= 10 and (y_up - y_low) <= 10
    ann.set_visible(visible)

ax.callbacks.connect('xlim_changed', on_lims_change)
ax.callbacks.connect('ylim_changed', on_lims_change)

plt.xlim([-5, 5])
plt.ylim([-5, 5])
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.