如何使用细化在网格上绘图?

问题描述 投票:1回答:1

Related question

我的数据以(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]

这里示出的是对应于上述伪数据的像素的期望位置和空间范围。

enter image description here

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

有没有办法在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)。位置始终指向像素的中心。

python matplotlib pixel
1个回答
1
投票

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

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()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.