【问题标题】:Plotting a heatmap in Python using matplotlib使用 matplotlib 在 Python 中绘制热图
【发布时间】:2020-03-31 10:53:39
【问题描述】:

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

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

一些指针

在数组“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。为什么我必须做meshgrip和reshape?

我是 Python 的新手,所以如果能提供更详细的回复会更好

【问题讨论】:

  • 您提供的代码中的哪一行您的脚本失败了?它在您的错误消息中声明它是第 1 行,但它也是此处显示的代码中的第 1 行吗?
  • 我认为错误发生在 Z=z.reshape(len(y1),len(x), order='F') 中。我不确定这段代码应该做什么,所以不能说如何解决这个问题。
  • @Solvalou : 代码在 -> Z=z.reshape(len(y1),len(x), order='F') 处失败
  • @Tobbor:该代码应该绘制热图。根据我的问题陈述,还有其他方法可以制作热图吗?
  • 如果 x 中的所有项目都不同,您将无法获得 2D 热图,因为您的数据仅弥补 1D 线。您能重新考虑一下您如何将数据显示为热图吗?

标签: python matplotlib heatmap


【解决方案1】:

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

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)

【讨论】:

    猜你喜欢
    • 2016-01-21
    • 2018-11-23
    • 2020-06-20
    • 1970-01-01
    • 2019-10-21
    • 2017-06-17
    • 2019-09-03
    • 1970-01-01
    • 2018-03-06
    相关资源
    最近更新 更多