python - 如何在网格上进行细化绘制?

标签 python matplotlib pixel

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)。位置始终引用像素的中心。

最佳答案

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

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

关于python - 如何在网格上进行细化绘制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53483513/

相关文章:

python - Emacs Pabbrev 和 Python

python - 带有OpenCV 3的OpenNI2

python - 我应该如何评论部分 Python 函数?

python-3.x - 属性错误 : module 'matplotlib' has no attribute 'scatter'

python - Pygame 将 28x28 像素缩放到 420x420

image - 在 python 中使用 PIL 模糊图像

internet-explorer - 有没有办法从 Internet Explorer 获取像素数据?

python - 删除 Dask 中的空分区

python - 调用 Python 函数而不向其传递参数 - animate(i)

python - Python 中带有渐变背景的点图?