Making an Array of Polygon "handles" in Python

Question:

I am making animations with large numbers of filled polygons. I am currently defining each polygon by copying the vertices from a standard profile shape, transforming each of the points into the proper location on the figure, then using a plt.fill operation to create the polygon, which is then cleared after each step of the animation. As I am working with hundreds of these polygons, allocating space for all of these vertices, doing the transformations, and making/clearing the figure every step is making this a rather computationally intensive process.

I understand that the end product of the fill operation is a Polygon, and that the polygon itself can be transformed and manipulated. So what I want to do is establish N polygons based on the vertex profile, and just update them with transformations. To do so I need to establish some sort of handle so I can reference polygon[i] at a later time. As I mentioned, I am working with hundreds, potentially thousands, of polygons, so I need to index them in some way.

I have tried doing the following (simplified code) to define the polygons:

import numpy as np
import matplotlib.pyplot as plt

n_poly = 10
poly = np.zeros(n_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[i] = plt.fill(x_profile, y_profile, closed = True)

But I get the following, which seems that the entire polygon construct is trying to be assigned to the array, not just a handle.

TypeError: float() argument must be a string or a number, not 'list'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/lib/python3.8/idlelib/run.py", line 559, in runcode
    exec(code, self.locals)
  File "/home/ThunderChicken/Test/test.py", line 18, in <module>
    poly[i] = plt.fill(x_profile, y_profile, closed = True)
ValueError: setting an array element with a sequence.

I have not seen examples with polygons referenced like this so I’m in the dark, but this seems like it would or should be a routine operation if I can sort out the syntax. The only examples I have seen are with a couple of individually named polygons where this wasn’t needed.

Asked By: Thunder Chicken

||

Answers:

NumPy arrays are made to store simple numerical values, not complex objects.

You want a list instead:

poly = []
for _ in range(n_poly):
    poly.append(plt.fill(x_profile, y_profile, closed=True))
Answered By: mkrieger1
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.