用python的matplotlib画等高线
对离散数据画等高线,填充颜色,并显示颜色条
- 生成网格,然后通过插值填充数据
- 对插值后的数据画等高线
- 根据最大值和最小值画colorbar
画等高线
# 产生网格,temp_data是n*3维的矩阵,temp_data[:,0]是x坐标,temp_data[:,1]是y坐标,# temp_data[:,2]是(x,y)位置上的温度
grid_x,grid_y=np.mgrid[np.min(temp_data[:,0]):np.max(temp_data[:,0]):5,np.min(temp_data[:,1]):np.max(temp_data[:,1]):5]
# 坐标数据
points = temp_data[:,0:2]
# 温度数据
z = temp_data[:,2]
# 在网格上线性插值,即温度值。边缘可能会是nan,因为边缘无法线性插值,可以用邻近插值nearest
grid_z = griddata(points, z, (grid_x, grid_y), method='linear')
fig = plt.figure()
# contourf对等高线间填充颜色,颜色是cmap。还有contour是画等高线,不填充
cs = plt.contourf(grid_x, grid_y ,grid_z, 15, alpha = 0.75, cmap = plt.cm.jet)
# 画colorbar
plt.colorbar()
plt.show()
单独画colorbar
fig = plt.figure()
# 指定colorbar显示在图像的哪一块区域
ax = fig.add_axes([0.83, 0.22, 0.03, 0.65])
# colorbar的颜色
cmap = plt.cm.jet
# colorbar的刻度,从最小值到最大值
norm = mpl.colors.Normalize(vmin = np.min(grid_z), vmax = np.max(grid_z))
# 可以设置颜色,刻度,刻度的方向等
cb = mpl.colorbar.ColorbarBase(ax, cmap = cmap, norm = norm, orientation = 'vertical')
plt.show()