Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib RegularPolyCollection with static (data like) sizes?

Is it possible to create a RegularPolyCollection with static sizes?

I'd like to give the size in data units, not in screen units. Just like the offsetts.

The target is to have an image of a camera with 1440 hexagonal Pixels with a diameter of 9.5 mm.

It is possible to achieve this with looping over 1440 Polygons but i was not successfull creating it with a PolyCollection which has big advantages, for creating colormaps etc.

Here is the code i use to plot the 1440 hexagons with static size:

for c, x, y in zip(pixel_color, pixel_x, pixel_y):
    ax.add_artist(
        RegularPolygon(
            xy=(x, y),
            numVertices=6,
            radius=4.75,
            orientation=0.,
            facecolor=c,
            edgecolor=edgecolor,
            linewidth=1.5,
        )
    )

And this code produces the same but with wrong and not static (in terms of data) sizes:

a = 1/np.sqrt(3) * 9.5

collection = RegularPolyCollection(
    numsides=6,
    rotation=0.,   
    sizes=np.ones(1440)*np.pi*a**2,  # tarea of the surrounding circle
    facecolors=pixel_colors,
    edgecolors="g",
    linewidth=np.ones(1440)*1.5,
    offsets=np.transpose([pixel_x, pixel_y]),
    transOffset=self.transData,
)

self.add_collection(collection)

How can I achieve the static sizes of the hexagons with the advantages of having a collection?

like image 360
MaxNoe Avatar asked Nov 01 '22 09:11

MaxNoe


1 Answers

I recently had the same problem. The solution is to simply use PatchCollection instead of RegularPolyCollection. The disadvantage is, however, that you have instantiate every single patch manually. Below you'll find a code example that plots 10,000 regular hexagons on a regular grid.

# imports
import matplotlib.pyplot as plt
from matplotlib.patches import RegularPolygon
from matplotlib.collections import PatchCollection
import numpy as np

# set up figure
fig, ax = plt.subplots(1)

# positions
pixel_x, pixel_y = np.indices((100, 100))
pixel_color = np.random.random_sample(30000).reshape(10000, 3)
dx = 4    # horizontal stride
dy = 5    # vertical stride 

# set static radius
poly_radius = 2.5

# list to hold patches
patch_list = []

# creat the patches
for c, x, y in zip(pixel_color, pixel_x.flat, pixel_y.flat):    
    patch_list.append(
            RegularPolygon(
                    xy=(x*dy, y*dy),
                    numVertices=6,
                    radius=poly_radius,
                    orientation=0.,
                    facecolor=c,
                    edgecolor='k'  
            )
    )


pc = PatchCollection(patch_list, match_original=True)
ax.add_collection(pc)

ax.axis([-3, 480, -3, 480])
plt.show()

On my machine this code takes about 2.8 seconds to render everything.

enter image description here

like image 159
MaxPowers Avatar answered Nov 15 '22 03:11

MaxPowers