我想使用 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()
Axes
类的“xlim_changed”和“ylim_changed”事件。下面,我调整了你的代码,以便
这可能还不完美,但我希望它能让您了解如何继续。
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()