【问题标题】:How to make 2D colored grid with 3 arrays如何使用 3 个数组制作 2D 彩色网格
【发布时间】:2017-04-27 14:48:57
【问题描述】:

我有三个长度相等的数组 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]

【问题讨论】:

  • 你首先必须对整个网格进行插值(例如检查 scipy 的 griddata),一旦你使用了 matplotlib 中的 imshowheatmap。 SO中有很多例子可以实现这一点。

标签: python arrays matplotlib multidimensional-array plot


【解决方案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()

【讨论】:

    猜你喜欢
    • 2017-09-22
    • 2023-03-28
    • 1970-01-01
    • 1970-01-01
    • 2011-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 1970-01-01
    相关资源
    最近更新 更多