使用随机数据和位置在 pyplot 中创建色图图

Creating a colourmap plot in pyplot with random data and positions

我想用颜色图绘制形状为 (100,3) 的地图(我们称之为测试图)。每行由 x 位置、y 位置和数据组成,全部随机绘制。

map_pos_x = np.random.randint(100, size=100)
map_pos_y = np.random.randint(100, size=100)
map_pos = np.stack((map_pos_x, map_pos_y), axis=-1)
draw = np.random.random(100)
draw = np.reshape(draw, (100,1))
testmap = np.hstack((map_pos, draw))

我不想使用散点图,因为地图位置应该模拟相机的像素。如果我尝试

plt.matshow(A=testmap)

我得到一张 100*2 的地图。但是,我想要一张 100*100 的地图。没有数据的位置可以是黑色的。我该怎么做?

编辑:我现在采用了以下内容:

grid = np.zeros((100, 100))
i=0

for pixel in map_pos:
    grid[pixel[0], pixel[1]] = draw[i]
    i=i+1

这产生了我想要的东西。之所以不在循环中自己绘制随机数,而是遍历现有数组"draw",是因为绘制的数字是先被操作的,所以我想有操作的自由"draw" 独立于循环。 此代码还生成双 entries/non-unique 对,这本身很好,但我想识别这些双对并为这些对添加 "draw"。我该怎么做?

一个解决方案是这样的:

import numpy as np
import matplotlib.pyplot as plt
import random
import itertools

#gets as input the size of the axis and the number of pairs  
def get_random_pairs(axis_range, count):
  numbers = [i for i in range(0,axis_range)]
  pairs = list(itertools.product(numbers,repeat=2))
  return random.choices(pairs, k=count)

object_positions = get_random_pairs(100,100) 

grid = np.zeros((100, 100))

for pixel in object_positions:
    grid[pixel[0],pixel[1]] = np.random.random()
    print(pixel)

plt.matshow(A=grid)

结果:

编辑: 由于网格初始化为零,因此只需将新值添加到旧值

n_pixels_x = 100
n_pixels_y = 100 
map_pos_x = np.random.randint(100, size=100)
map_pos_y = np.random.randint(100, size=100)
map_pos = np.stack((map_pos_x, map_pos_y), axis=-1)
draw = np.random.random(100)
draw = np.reshape(draw, (100,1))
testmap = np.hstack((map_pos, draw))
grid = np.zeros((n_pixels_x, n_pixels_y))


for pixel in map_pos:
    grid[pixel[0], pixel[1]] = grid[pixel[0], pixel[1]] + draw[i]


plt.matshow(A=grid)

您可以先创建空像素,使用零(获得 "lowest" 颜色)或 NaN(这些像素将不可见)。然后你可以使用 numpy 的智能索引来填充值。为此,重要的是 map_pos_xmap_pos_y 是正确范围内的整数坐标。

import numpy as np
import matplotlib.pyplot as plt

map_pos_x = np.random.randint(100, size=100)
map_pos_y = np.random.randint(100, size=100)
draw = np.random.random(100)

# testmap = np.full((100,100), np.nan)
testmap = np.zeros((100,100))
testmap[map_pos_x, map_pos_y] = draw

plt.matshow(testmap)
plt.show()

PS:关于你的新问题,要计算有多少xy位置重合,可以使用np.histogram2d。结果也可以通过 matshow 绘制。一个好处是 xy 值不需要是整数:它们将根据它们的舍入值求和。

如果每个xy位置也有值,比如题中的数组draw,可以传为np.histogram2d(...., weights=draw).

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(1234)

N = 100
map_pos_x = np.random.randint(N, size=10000)
map_pos_y = np.random.randint(N, size=len(map_pos_x))

fig, (ax1, ax2) = plt.subplots(ncols=2)

testmap1, xedges, yedges = np.histogram2d(map_pos_x, map_pos_y, bins=N, range=[[0, N - 1], [0, N - 1]])

ax1.matshow(testmap1)

plt.show()

为了展示会发生什么,这里有一个 N=10 和左边 matshow 的测试。右边是一个带有半透明点的散点图,当有更多的点重合时,它们会变得更暗。