在 matplotlib 中使用 3D 数据生成热图

2023-11-26

我有一个函数returnValuesAtTime返回三个列表 -x_vals,y_vals and swe_vals。所有三个列表的长度相同,并且每个元素swe_vals对应于一个x-value from x_vals and a y-value from y_vals。我希望生成一个带有图例的热图,该图例使用(x,y)坐标和swe_vals作为强度。

我写了以下代码:

def plotValuesAtTimeMap(t):
    x_vals,y_vals,swe_vals=returnValuesAtTime(t)
    x_points=len(x_vals)
    y_points=len(y_vals)
    xx=np.linspace(x_vals[0],x_vals[-1],x_points)
    yy=np.linspace(y_vals[0],y_vals[-1],y_points)
    fig,ax=plt.subplots()
    im=ax.pcolormesh(xx,yy,z)
    fig.colorbar(im)
    ax.axis('tight')
    plt.show()

一旦使用获得三个列表returnValuesAtTime(t),我取长度x_vals and y_vals。然后,我使用它们生成 x 和 y 方向的间距,限制是第一个和最后一个元素x_vals and y_vals。然后我尝试生成colormesh。但这给了我一个空虚的colormesh没有价值观。

可能出了什么问题?将使用 3Dnumpy数组而不是三个列表可以解决问题吗?

每个列表的前 10 个元素是:

x_vals[0:10]

[439936.86573189893,
 439936.86573189893,
 439936.86573189893,
 439936.86573189893,
 439936.86573189893,
 439936.86573189893,
 439936.86573189893,
 439936.86573189893,
 439936.86573189893,
 439936.86573189893]

y_vals[0:10]

[4514018.2797159087,
 4513898.2797159087,
 4513778.2797159087,
 4513658.2797159087,
 4513538.2797159087,
 4513418.2797159087,
 4513298.2797159087,
 4513178.2797159087,
 4513058.2797159087,
 4512938.2797159087]

swe_vals[0:10]

[2.7520323,
 2.7456229,
 2.7456021,
 2.745455,
 2.7478349,
 2.7445269,
 2.7484877,
 2.7524617,
 2.75491,
 2.7509627]

Edit:

我添加了一个散点图,显示下面的 (x,y) 网格范围:

enter image description here

x 和 y 值位于列表中,每个长度为 6804。每个 (x,y) 点在单独的列表中都有一个对应的 z 值,该列表的长度也是 6804。为了澄清我希望实现的目标,我想生成一个类似热图的图,其中 z 轴的大小由图中每个网格的颜色表示。如下所示:

enter image description here

在示例图中,所有 z 值都相同。因此整个网格空间的颜色是相同的。

编辑新的结果情节(根据成员CT Zhu的建议):

enter image description here


看起来如果重塑x, y, z对于方阵,你可以做contourf plot:

In [7]:X
Out[7]:
array([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
       [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]])

In [8]:Y
Out[8]:
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2, 2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3, 3, 3, 3, 3, 3],
       [4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
       [5, 5, 5, 5, 5, 5, 5, 5, 5, 5],
       [6, 6, 6, 6, 6, 6, 6, 6, 6, 6],
       [7, 7, 7, 7, 7, 7, 7, 7, 7, 7],
       [8, 8, 8, 8, 8, 8, 8, 8, 8, 8],
       [9, 9, 9, 9, 9, 9, 9, 9, 9, 9]])

plt.contourf(X,Y,np.random.random((10,10))) #reshape Z too!
plt.colorbar()

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 matplotlib 中使用 3D 数据生成热图 的相关文章

随机推荐