【问题标题】:How to update PolyCollection in matplotlib如何在 matplotlib 中更新 PolyCollection
【发布时间】:2021-11-18 08:19:31
【问题描述】:

我想知道,是否有办法重绘已经创建的 PolyCollection。

MWP

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(0.0, 2, 0.01)
y = np.sin(2*np.pi*x)

fig, (ax,ax2) = plt.subplots(1,1)

polycolelction = ax.fill_between(x, y)

for i in range(10):
    y = 1.2*np.sin(i*np.pi*x)

    # here should be data update, probably something like set_offset or set_verts?
    polycolelction.set_verts([x,y])
    fig.canvas.draw()
    fig.canvas.flush_events()

【问题讨论】:

标签: python numpy matplotlib


【解决方案1】:

从头开始创建多边形然后更新其顶点可能更容易。这样,我们就可以精确控制顶点的数量以及多边形的表示方式。

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection

x = np.arange(0.0, 2, 0.01)
y = np.sin(2 * np.pi * x)

fig, ax = plt.subplots()

points = np.array([x, y]).T
points = np.vstack([points, [points[-1, 0], 0], [points[0, 0], 0]])
polycollection = PatchCollection([Polygon(points, closed=True)])
pathcollection = ax.add_collection(polycollection)
ax.set_xlim(x[0], x[-1])
ax.set_ylim(-1.3, 1.3)

for i in range(10):
    y = 1.2 * np.sin(i * np.pi * x)
    points = np.array([x, y]).T
    points = np.vstack([points, [points[-1, 0], 0], [points[0, 0], 0]])
    pathcollection.get_paths()[0].vertices = points
    fig.canvas.draw()
    fig.canvas.flush_events()

【讨论】:

    猜你喜欢
    • 2020-11-30
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    • 2020-07-16
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 2010-12-26
    相关资源
    最近更新 更多