在python中绘制热图 [英] Drawing heat map in python
问题描述
我有两个列表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的尺寸比示例中的尺寸高得多.
I'm having two lists x, y representing coordinates in 2D. For example x = [1,4,0.5,2,5,10,33,0.04]
and y = [2,5,44,0.33,2,14,20,0.03]
. x[i]
and y[i]
represent one point in 2D. Now I also have a list representing "heat" values for each (x,y) point, for example z = [0.77, 0.88, 0.65, 0.55, 0.89, 0.9, 0.8,0.95]
. Of course x,y and z are much higher dimensional than the example.
现在,我想在2D中绘制一个热图,其中x和y代表轴坐标,z代表颜色.如何在python中完成?
Now I would like to plot a heat map in 2D where x and y represents the axis coordinates and z represents the color. How can this be done in python?
推荐答案
此代码会产生热图.有了更多的数据点,该图就开始看起来非常漂亮,而且我发现,即使超过10万个点,总体上它也非常快.
This code produces a heat map. With a few more data points, the plot starts looking pretty nice and I've found it to be very quick in general even for >100k points.
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()
产生此图像:
或者如果您正在寻找更渐变的颜色,请将tricontourf行更改为此:
or if you're looking for a more gradual color change, change the tricontourf line to this:
CS = ax.tricontourf(x, y, z, np.linspace(min(levels),max(levels),256), cmap=cmap)
,然后绘图将变为:
这篇关于在python中绘制热图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!