Polygon animation#

Polygon animation example that changes the polygon data. Random points are generated by sampling from a 2D gaussian and a polygon is updated to visualize a convex hull for the sampled points.

polygon animation
/home/runner/work/fastplotlib/fastplotlib/fastplotlib/graphics/features/_base.py:18: UserWarning: casting float64 array to float32
  warn(f"casting {array.dtype} array to float32")

# test_example = false

import numpy as np
from scipy.spatial import ConvexHull
import fastplotlib as fpl


def points_to_hull(points) -> np.ndarray:
    hull = ConvexHull(points, qhull_options="Qs")
    return points[hull.vertices]


figure = fpl.Figure(size=(700, 560))


cov = np.array([[1, 0], [0, 1]])

# sample points from a 2d gaussian
samples1 = np.random.multivariate_normal((0, 0), cov, size=20)
samples2 = np.random.multivariate_normal((5, 0), cov, size=50)

# add the convex hull as a polygon
polygon1 = figure[0, 0].add_polygon(
    points_to_hull(samples1), colors="cyan", alpha=0.7, alpha_mode="blend"
)
# add the sampled points
scatter1 = figure[0, 0].add_scatter(
    samples1, sizes=8, colors="blue", alpha=0.7, alpha_mode="blend"
)

# add the second gaussian and convex hull polygon
polygon2 = figure[0, 0].add_polygon(
    points_to_hull(samples2), colors="magenta", alpha=0.7, alpha_mode="blend"
)
scatter2 = figure[0, 0].add_scatter(
    samples2, sizes=8, colors="r", alpha=0.7, alpha_mode="blend"
)


def animate():
    # set new scatter data
    scatter1.data[:, :-1] += np.random.normal(0, 0.05, size=samples1.size).reshape(
        samples1.shape
    )
    # set convex hull with new polygon vertices
    polygon1.data = points_to_hull(scatter1.data[:, :-1])

    # set the other scatter and polygon
    scatter2.data[:, :-1] += np.random.normal(0, 0.05, size=samples2.size).reshape(
        samples2.shape
    )
    polygon2.data = points_to_hull(scatter2.data[:, :-1])


figure.show()
figure[0, 0].camera.width = 10
figure[0, 0].camera.height = 10

figure.add_animations(animate)


# NOTE: fpl.loop.run() should not be used for interactive sessions
# See the "JupyterLab and IPython" section in the user guide
if __name__ == "__main__":
    print(__doc__)
    fpl.loop.run()

Total running time of the script: (0 minutes 18.397 seconds)

Gallery generated by Sphinx-Gallery