在Python中使用插值绘制热图或颜色图

时间:2020-06-22 20:22:27

标签: python matplotlib interpolation heatmap colormap

我需要在python中创建“ heatmap”或“ colormap”。我有三个python列表,分别是:X_COORDINATE,Z_COORDINATE和C_I。 X_COORDINATE和Z_COORDINATE列表包含我具有特定数据点(存储在C_I列表中)的x和z坐标。 C_I列表包含我需要在相应坐标处绘制到x-z网格上的值。

热图/颜色图需要在C_I列表中已知和包含的点之间进行插值,以使图平滑,而不是正方形。我不能共享代码或源数据,因为这很敏感。但是,为了理解如何编码这些映射之一,假定:

X = [1.1, 1.5, 2.0, 3.0, 4.0, 5.0, 1.1, 1.5, 2.0, 3.0, 4.0, 5.0, 1.1, 1.5, 2.0, 3.0, 4.0, 5.0, 0.0, 0.5, 1.0, 1.1, 1.5, 2.0, 3.0, 4.0, 5.0, 0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0]

Z = [0, 0, 0, 0, 0, 0, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 1, 1, 2.1, 2.1, 2.1, 2.1, 2.1, 2.1, 2.1, 2.1, 2.1, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5, 2.5]

C_I = [1.02414267447743, 0.210700871073941, 0.156586042435711, 0.109151033138569, 0.2279728779957, 0.204768257586954, 1.09037445301743, 0.287155868433615, 0.211257395413685, 0.132554129593619, 0.0900680495011601, 0.194608837248807, 1.34397119257655, 0.1201882143371, 0.17555070608144, 0.127220190160657, 0.204384526301353, 0.197414938747342, 0.195583977408476, 0.148150828086297, 0.183751866814816, 0.134858902076203, 0.183027629350907, 0.180267135381046, 0.0876356087026242, 0.183285092770786, 0.165502978081942, 0.0487725567447014, 0.172053559692846, 0.142204671797215, 0.166163224221791, 0.249334486033046, 0.150888488422605, 0.259452257883415]

因此,X_COORDINATE列表中的第零个元素是第一个数据点的x坐标,Z_COORDINATE列表中的第零个元素是第一个数据点的z坐标,而C_I列表中的第零个元素是值必须为第一个点绘制。

我想在x轴上使用X_COORDINATE,在z轴上使用Z_COORDINATE,并且将地图内部的相应C_I值着色。为了清楚起见,我希望地图类似于以下所附图像;尽管我希望X轴和Z轴刻度线以及相关的颜色条出现。我该怎么做?

网格在x方向上应为5个单位,在z方向(y轴)上应为2.5个单位

sample heatmap

1 个答案:

答案 0 :(得分:1)

因此,我找到了解决方案。供以后参考,此代码应为遇到相同问题的人员提供所需的信息。我在plot.imshow()函数中添加了“插值”参数,例如:

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm
from scipy.interpolate import interp2d

x_list = np.array(X_COORDINATE)
z_list = np.array(Z_COORDINATE)
C_I_list = np.array(C_I)

#   f will be a function with two arguments (x and z coordinates),
# but those can be array_like structures too, in which case the
# result will be a matrix representing the values in the grid 
# specified by those arguments
f = interp2d(x_list,z_list,C_I_list,kind="linear")

x_coords = np.arange(min(x_list),max(x_list)+1)
z_coords = np.arange(min(z_list),max(z_list)+1)
c_i = f(x_coords,z_coords)

fig = plt.imshow(c_i,
           extent=[min(x_list),max(x_list),min(z_list),max(z_list)],
           origin="lower", interpolation='bicubic')

# Show the positions of the sample points, just to have some reference
fig.axes.set_autoscale_on(False)
plt.scatter(x_list,z_list,400,facecolors='none')
plt.colorbar()
plt.show()

有人知道我该如何更改地图上颜色的分辨率,以便更好地查看整个地图中0和1值之间的变化吗?

现在,地图如下所示:

updated heatmap