Home > Software design >  How does one reference a Polygon in a list, transform it, and then return it to the list in Python?
How does one reference a Polygon in a list, transform it, and then return it to the list in Python?

Time:12-27

I am working with animating a large number of filled polygons in Python. What I have been doing is defining the vertices outlining each shape, transforming the vertices, then filling them, and then clearing them and repeating the process for each frame of the animation, and it's getting rather computationally expensive and slow. What I am looking to do to streamline the code is to establish the polygons initially, and then just update the transformations between the frames.

I've determined that I can store the polygons in a list, but I am not clear on how I can reference individual polygons from that list, apply transformations, and then return them to the list.

I've tried this example code:

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

n_poly = 10
poly = []

fig = plt.figure(frameon=False)
fig.set_size_inches(2.0, 2.0)
ax = plt.axes()

#makes vertices forming a simple square

x_profile = [0, 1, 1, 0]
y_profile = [0, 0, 1, 1]

for i in range(n_poly):

    poly.append(plt.fill(x_profile, y_profile, closed = True))

rotation = mpl.transforms.Affine2D().rotate(5)

for i in range(n_poly):
    
    polygon = poly[i]
    polygon.set_transform(rotation)
    poly[i] = polygon

It fails in the second loop with the error "AttributeError: 'list' object has no attribute 'set_transform'".

Similarly, polygon[i].set_transform(rotation) or poly[i].set_transform(rotation) in the second loop doesn't work.

CodePudding user response:

fill() returns a list of Polygons, so poly is a list of lists. So you can do something like

poly[0][0].set_transform(rotation)
poly[1][0].set_transform(rotation)

etc.

  • Related