在pyplot中创建带有随机数据和位置的色图图

问题描述 投票:0回答:2

我想绘制一个带有颜色图的形状(100,3)的贴图(我们称之为testmap)。每行都由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”的自由”,与循环无关。这段代码还会产生双输入/非唯一对,这本身就可以,但是我想识别这些双对并为这些对加“绘制”。我该怎么办?

python matplotlib colormap
2个回答
0
投票

解决方案是这样:

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)

结果:enter image description here


0
投票

您可以先创建带有零(获得“最低”颜色)或NaN(这些像素将不可见)的空像素。然后,您可以使用numpy的智能索引来填充值:

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(A=testmap)
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.