Matplotlib RegularPolyCollection 具有静态(类似数据)大小?

Max*_*Noe 5 python matplotlib

是否可以创建具有静态大小的 RegularPolyCollection?

我想以数据单位而不是屏幕单位给出大小。就像偏移量一样。

目标是拥有一个直径为 9.5 毫米的具有 1440 个六边形像素的相机图像。

可以通过循环超过 1440 个多边形来实现这一点,但我没有成功地使用具有很大优势的 PolyCollection 创建它,用于创建颜色图等。

这是我用来绘制静态大小的 1440 个六边形的代码:

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,
        )
    )
Run Code Online (Sandbox Code Playgroud)

并且此代码产生相同但错误且非静态的(就数据而言)大小:

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)
Run Code Online (Sandbox Code Playgroud)

如何利用集合的优势实现六边形的静态大小?

Max*_*ers 1

我最近也遇到了同样的问题。解决方案是简单地使用PatchCollection而不是RegularPolyCollection. 然而,缺点是您必须手动实例化每个补丁。下面您将找到一个在规则网格上绘制 10,000 个规则六边形的代码示例。

# 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()
Run Code Online (Sandbox Code Playgroud)

在我的机器上,这段代码大约需要 2.8 秒来渲染所有内容。

在此输入图像描述