在python中绘制热图

时间:2017-01-31 16:08:34

标签: python matplotlib heatmap

我有两个列表x,y表示2D中的坐标。例如x = [1,4,0.5,2,5,10,33,0.04]y = [2,5,44,0.33,2,14,20,0.03]x[i]y[i]代表2D中的一个点。现在我还有一个列表,表示每个(x,y)点的“加热”值,例如z = [0.77, 0.88, 0.65, 0.55, 0.89, 0.9, 0.8,0.95]。当然,x,y和z的维度比例子高得多。

现在我想在2D中绘制热图,其中x和y代表轴坐标,z代表颜色。怎么能在python中完成呢?

2 个答案:

答案 0 :(得分:4)

此代码生成热图。有了更多的数据点,情节开始看起来非常好,我发现它一般非常快,即使是> 100k点。

import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
import math

x = [1,4,0.5,2,5,10,33,0.04]
y = [2,5,44,0.33,2,14,20,0.03]
z = [0.77, 0.88, 0.65, 0.55, 0.89, 0.9, 0.8, 0.95]
levels = [0.7, 0.75, 0.8, 0.85, 0.9]

plt.figure()
ax = plt.gca()
ax.set_aspect('equal')
CS = ax.tricontourf(x, y, z, levels, cmap=plt.get_cmap('jet'))
cbar = plt.colorbar(CS, ticks=np.sort(np.array(levels)),ax=ax, orientation='horizontal', shrink=.75, pad=.09, aspect=40,fraction=0.05)
cbar.ax.set_xticklabels(list(map(str,np.sort(np.array(levels)))))  # horizontal colorbar
cbar.ax.tick_params(labelsize=8) 
plt.title('Heat Map')
plt.xlabel('X Label')
plt.ylabel('Y Label')

plt.show()

制作此图片:

enter image description here

或者如果您正在寻找更渐进的颜色变化,请将tricontourf线更改为:

CS = ax.tricontourf(x, y, z, np.linspace(min(levels),max(levels),256), cmap=cmap)

然后情节将变为:

enter image description here

答案 1 :(得分:1)

基于this answer,您可能希望执行以下操作:

import numpy as np
from matplotlib.mlab import griddata
import matplotlib.pyplot as plt 
xs0 = [1,4,0.5,2,5,10,33,0.04]
ys0 = [2,5,44,0.33,2,14,20,0.03]
zs0 = [0.77, 0.88, 0.65, 0.55, 0.89, 0.9, 0.8,0.95]   
N = 30j
extent = (np.min(xs0),np.max(xs0),np.min(ys0),np.max(ys0))  
xs,ys = np.mgrid[extent[0]:extent[1]:N, extent[2]:extent[3]:N]    
resampled = griddata(xs0, ys0, zs0, xs, ys, interp='linear')   
plt.imshow(np.fliplr(resampled).T, extent=extent,interpolation='none')
plt.colorbar()

enter image description here

此处的示例也可能有所帮助:http://matplotlib.org/examples/pylab_examples/griddata_demo.html