python绘制热力图

  在python中绘制热力图大致有两种方法通过matplotlib库的imshow函数以及seaborn库的heatmap函数,通过笔者尝试,seaborn库更加灵活,本篇以seaborn为准

  源代码如下:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

sns.set()
plt.rcParams['font.sans-serif']='SimHei'#设置中文显示,必须放在sns.set之后
np.random.seed(0)
uniform_data = np.random.rand(10, 12) #设置二维矩阵
f, ax = plt.subplots(figsize=(9, 6))

#heatmap后第一个参数是显示值,vmin和vmax可设置右侧刻度条的范围,
#参数annot=True表示在对应模块中注释值
# 参数linewidths是控制网格间间隔
#参数cbar是否显示右侧颜色条,默认显示,设置为None时不显示
#参数cmap可调控热图颜色,具体颜色种类参考:https://blog.csdn.net/ztf312/article/details/102474190
sns.heatmap(uniform_data, ax=ax,vmin=0,vmax=1,cmap='YlOrRd',annot=True,linewidths=2,cbar=True)

ax.set_title('hello') #plt.title('热图'),均可设置图片标题
ax.set_ylabel('y_label')  #设置纵轴标签
ax.set_xlabel('x_label')  #设置横轴标签

#设置坐标字体方向,通过rotation参数可以调节旋转角度
label_y = ax.get_yticklabels()
plt.setp(label_y, rotation=360, horizontalalignment='right')
label_x = ax.get_xticklabels()
plt.setp(label_x, rotation=45, horizontalalignment='right')

plt.show()

  效果图如下:
在这里插入图片描述
参考博客:https://blog.csdn.net/sunchengquan/article/details/78573244

猜你喜欢

转载自blog.csdn.net/gls_nuaa/article/details/113090701