当前位置:主页 > 软件编程 > Python代码 >

python使用matplotlib绘制热图

时间:2021-02-05 09:38:19 | 栏目:Python代码 | 点击:

python常用的绘图库就是matplotlib,今天在给公司绘图时,偶然间发现matplotlib可以绘制热图,并且十分简洁,拿出来跟大家分享一下。(由于涉及到公司数据问题,这里采用随机数生成数据进行实验)

import random
from matplotlib import pyplot as plt
from matplotlib import cm
from matplotlib import axes
from matplotlib.font_manager import FontProperties
font = FontProperties(fname='/Library/Fonts/Songti.ttc')
 
def draw():
 #定义热图的横纵坐标
 xLabel = ['A','B','C','D','E']
 yLabel = ['1','2','3','4','5']
 
 #准备数据阶段,利用random生成二维数据(5*5)
 data = []
 for i in range(5):
  temp = []
  for j in range(5):
   k = random.randint(0,100)
   temp.append(k)
  data.append(temp)
 
 #作图阶段
 fig = plt.figure()
 #定义画布为1*1个划分,并在第1个位置上进行作图
 ax = fig.add_subplot(111)
 #定义横纵坐标的刻度
 ax.set_yticks(range(len(yLabel)))
 ax.set_yticklabels(yLabel, fontproperties=font)
 ax.set_xticks(range(len(xLabel)))
 ax.set_xticklabels(xLabel)
 #作图并选择热图的颜色填充风格,这里选择hot
 im = ax.imshow(data, cmap=plt.cm.hot_r)
 #增加右侧的颜色刻度条
 plt.colorbar(im)
 #增加标题
 plt.title("This is a title", fontproperties=font)
 #show
 plt.show()
 
d = draw()

效果图如下:

为了更清晰地看出二维数值矩阵与热图之间的对应关系,我们输出二维矩阵:

[[17, 96, 11, 99, 83], [18, 17, 58, 18, 80], [87, 79, 15, 53, 4], [86, 53, 48, 36, 23], [25, 4, 94, 100, 71]]

从对应关系我们可以看出,图像的左上角为坐标原点,第一行对应的二维矩阵中的第一行数据,以此类推。
同时我们可以看出数值越大的单元,对应热图中的颜色越深。其实这是一个可选项,只需要改变im = ax.imshow(data, cmap=plt.cm.hot_r)中的参数cmap为hot_r,其中_r的意思是就是按照颜色越深,数值越大,如果想数值越大,颜色越浅,只需要去掉_r,直接为hot就行。同时这个hot是热图配色的其中一个主题,主题色参数可选:

右侧的颜色刻度条colorbar也是可选的,如果不写就不会显示

您可能感兴趣的文章:

相关文章