首页 > 解决方案 > 如何在网格上进行细化?

问题描述

相关问题

我的数据以 (3 × N) 数组的形式出现

[[x_0, ..., x_N-1],
 [y_0, ..., y_N-1],
 [z_0, ..., z_N-1]]

我想绘制它,以便前两行编码像素的 X、Y 位置,第三行设置像素的颜色。

但是,我不希望发生任何插值。相反,空间是由所有点都位于网格上的事实平铺的,较低的分区是原始网格的细化。这是一些虚拟数据

[[4, 12, 24,  4, 12, 20, 28,  8, 18, 22, 28, 17, 19, 22, 17, 19],  # X
 [4,  4,  8, 12, 12, 20, 20, 24, 26, 26, 28, 29, 29, 30, 31, 31],  # Y
 [1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16]]  # Z (color)

这些像素有大小

D = [8,  8, 16,  8,  8,  8,  8, 16,  4,  4,  8,  2,  2,  4,  2,  2]

这里说明的是与上述虚拟数据相对应的像素的所需位置和空间范围。

在此处输入图像描述

现在,我可以插入我的数据以匹配最好的网格点,但这将是低效的并且不是很优雅。我的网格的某些区域可能比其他区域更精细。

有没有办法在 matplotlib 中制作这种情节?

编辑为了澄清,细化位置 (x, y) 大小 (d×d) 的像素在 (x - d/4, y - d/4), (x + d/4, y - d) 位置提供 4 个像素/4), (x - d/4, y + d/4),(x + d/4, y + d/4),每个尺寸为 (d/2 × d/2)。位置总是指像素的中心。

标签: pythonmatplotlibpixel

解决方案


没有内置函数可以绘制像问题中指定的那样的不规则网格。解决方案是定义具有各自边缘的“像素”集合。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import PolyCollection
from matplotlib.ticker import MultipleLocator

x =  np.array([4, 12, 24,  4, 12, 20, 28,  8, 18, 22, 28, 17, 19, 22, 17, 19])  # X
y =  np.array([4,  4,  8, 12, 12, 20, 20, 24, 26, 26, 28, 29, 29, 30, 31, 31])  # Y
z =  np.array([1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16])  # Z (color)
D =  np.array([8,  8, 16,  8,  8,  8,  8, 16,  4,  4,  8,  2,  2,  4,  2,  2])


def irregularmesh(x, y, s, c, ax=None, **kwargs):
    xedge = np.c_[-s, s, s, -s]/2. + np.atleast_2d(x).T
    yedge = np.c_[-s, -s, s, s]/2. + np.atleast_2d(y).T
    xy = np.stack((xedge,yedge), axis=2)

    # Create collection of rectangles.
    pc = PolyCollection(xy, closed=True, **kwargs)
    pc.set_array(c)
    ax = ax or plt.gca()
    ax.add_collection(pc)
    return pc

######## Plotting ################
fig, ax = plt.subplots()

pc = irregularmesh(x, y, D, z, ax=ax, linewidth=0, cmap="inferno")
fig.colorbar(pc, ax=ax)

ax.margins(0)
ax.autoscale()

for axis in [ax.xaxis, ax.yaxis]:
    axis.set_major_locator(MultipleLocator(4))
plt.show()

在此处输入图像描述


推荐阅读