使用matplotlib在Python中绘制热图

时间:2019-12-06 12:33:37

标签: python matplotlib heatmap

我是Python的新用户,在使用matplotlib在Python中绘制热图时需要帮助

我有三个向量[x,y,z],每个向量有7700个元素。我从Google搜索中获得了绘制热图的代码(见下文),但最终出现了错误

一些指针

在数组“ x”中,所有项目都不相同

在数组“ y”中,并非所有值都不同

在数组“ z”中,并非所有值都不同

x = mdf_merged.get('Signal_x').samples  # define the x array
y = mdf_merged.get('Signal_y').samples  # define the y array
z = mdf_merged.get('Signal_z').samples  # define the z array

x=np.unique(x)
x = np.unique(x)
y1, yind = np.unique(y, return_index=True)
X,Y = np.meshgrid(x,y[sorted(yind)])
Z=z.reshape(len(y1),len(x), order='F')
plt.pcolormesh(X,Y,Z)
plt.colorbar()
plt.xlabel("X-values")
plt.ylabel("Y-values")

我最终遇到此错误

Traceback (most recent call last):
  File "<input>", line 1, in <module>
ValueError: cannot reshape array of size 7700 into shape (6447,7700)

所以我的问题是

a)这可能是什么原因和可能的解决方案?

b)为什么不能直接取x,y和z。为什么我必须做网状网格并重塑形状?

我是Python的新手,所以稍加详细的答复就可以了

1 个答案:

答案 0 :(得分:0)

因此,在社区的帮助下,我能够更接近解决方案。我所做的是

import numpy as np
from scipy.interpolate import griddata
import matplotlib.pyplot as plt

x = mdf_merged.get('VariableX').samples
y = mdf_merged.get('VariableY').samples
z = mdf_merged.get('VariableZ').samples
###
xi = np.linspace(min(x),max(x),10)
yi = np.linspace(min(y),max(y),20)
zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='linear')
plt.pcolormesh(xi, yi, zi)