如何使用3个数组制作2D彩色网格

时间:2017-04-27 14:48:58

标签: python arrays matplotlib multidimensional-array plot

我有三个长度相等的x,y和z数组。 x和y数组是网格的x轴和y轴。 z数组将确定网格块的颜色。例如,

x = [10, 10, 10, 20, 20, 20, 30, 30, 30]
y = [10, 20, 30, 10, 20, 30, 10, 20, 30]
z = [99, 54, 32, 67, 71, 88, 100, 15, 29]

很容易制作3D图形

ax.plot_trisurf(x, y, z, cmap=cm.RdYlGn)

ax.bar3d(x, y, [0] * len(x), 100, 100, z, cmap=cm.RdYlGn)

但我正在寻找像this grid

这样的东西

另一个问题是我生成z数组的方式,它不是按索引顺序排列的。所以我的x,y和z数组看起来像这样。

x = [30, 10, 20, 20, 30, 10, 10, 30, 20]
y = [10, 20, 30, 10, 30, 30, 10, 20, 20]
z = [100, 54, 88, 67, 29, 32, 99, 15, 71]

1 个答案:

答案 0 :(得分:1)

以下是针对您的具体问题的一个小示例。我将您的x和y索引转换为查看数据的数组中的位置 - 您可能需要自己更改它。

import numpy as np
import matplotlib.pyplot as plt

x = [10, 10, 10, 20, 20, 20, 30, 30, 30]
y = [10, 20, 30, 10, 20, 30, 10, 20, 30]
z = [99, 54, 32, 67, 71, 88, 100, 15, 29]

# Convert x/y to indices. This only works if you have a rigid grid (which seems to be the case, but you might have to change the transform for your case)
x = (np.array(x)/10 - 1).astype(int)
y = (np.array(y)/10 - 1).astype(int)

# Create the image. Default color is black
z_im = np.zeros((x.max() + 1, y.max() + 1, 3))

# Go through z and color acoordingly -- only gray right now
for i, v in enumerate(z):
    z_im[x[i], y[i]] = (v, v, v)

fig, ax = plt.subplots()
ax.imshow(z_im)
plt.show()

enter image description here