移动补丁而不是移除i

2024-09-30 22:22:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张逐渐显现的图表。因为这应该发生在一个巨大的数据集和多个子批中,所以我计划移动这个patch,而不是为了加速代码而删除它并从头开始绘制。在

我的问题与this question相似。然而,我无法解决它。在

下面是一个最小工作示例:

import numpy as np
import matplotlib.pyplot as plt

nmax = 10
xdata = range(nmax)
ydata = np.random.random(nmax)

fig, ax = plt.subplots()
ax.plot(xdata, ydata, 'o-')
ax.xaxis.set_ticks(xdata)
plt.ion()

i = 0
while i <= nmax:
    # ------------ Here I would like to move it rather than remove and redraw.
    if i > 0:
        rect.remove()
    rect = plt.Rectangle((i, 0), nmax - i, 1, zorder = 10)
    ax.add_patch(rect)
    # ------------
    plt.pause(0.1)
    i += 1

plt.pause(3)

Tags: 数据rectimportasnp图表pltrandom
1条回答
网友
1楼 · 发布于 2024-09-30 22:22:00

也许这对你有用。您只需更新其位置和宽度(使用rect.set_x(left_x)rect.set_width(width)),而不是移除补丁,然后重新绘制画布。尝试用以下内容替换循环(请注意,Rectangle在循环之前创建了一次):

rect = plt.Rectangle((0, 0), nmax, 1, zorder=10)
ax.add_patch(rect)

for i in range(nmax):
    rect.set_x(i)
    rect.set_width(nmax - i)
    fig.canvas.draw()
    plt.pause(0.1)

相关问题 更多 >