主页 M

python数据可视-热力图

2022-08-30 网页编程网 网页编程网

1.实例

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import cm
from matplotlib import axes

#plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文
#plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

def draw(xLabel,yLabel,heatlist,title):
    #作图阶段
    fig = plt.figure(dpi =200)
    #定义画布为1*1个划分,并在第1个位置上进行作图
    ax = fig.add_subplot(111)
    #定义横纵坐标的刻度
    ax.set_xticks(np.arange(len(xLabel)), labels=xLabel)
    ax.set_yticks(np.arange(len(yLabel)), labels=yLabel)
    #作图并选择热图的颜色填充风格,这里选择hot
    im = ax.imshow(heatlist, cmap=plt.cm.hot_r)

    # Rotate the tick labels and set their alignment.
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right",rotation_mode="anchor")
    # Loop over data dimensions and create text annotations.
    for i in range(len(yLabel)):
        for j in range(len(xLabel)):
            text = ax.text(j, i, heatlist[i, j],ha="center", va="center", color="w")
    #增加右侧的颜色刻度条
    plt.colorbar(im,fraction=0.025, pad=0.05)
    #增加标题
    plt.title(title)
    plt.xlabel(u"Time(s)",fontsize=15) #X轴标签
    plt.ylabel("Throughput (×10 Mb/s)",fontsize=15) #Y轴标签
    #show
    plt.show()
    
heatlist1 = np.array([[1, 0, 2, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 2, 0],
    [0, 0, 1, 0, 0, 1, 0, 2, 0, 0, 1, 0, 0, 1, 2, 4, 4, 3, 7, 10, 2, 0, 1, 3],
    [25, 8, 0, 6, 7, 12, 6, 7, 19, 1,  4, 0, 3,  3,  6,  8, 21, 9, 0, 2, 5, 5, 4, 23],
    [3, 4,6, 16, 38, 21, 8, 2, 3, 9, 17, 7, 12, 13, 19, 35, 42, 12, 1,  8, 17,  5, 28, 21],
    [27, 24, 5, 24, 28, 23, 23, 45, 93, 59, 56, 31, 12, 20, 16, 23, 21,  20,  6,  4, 15, 16, 11,  8],
    [11,  7, 21, 18, 35, 79, 59, 30, 14, 22, 38, 13, 23, 29, 42, 61, 80,  74, 31, 19, 42, 60, 69, 49],
    [22, 15,  6, 15,  3,  4, 13,  5, 13, 12, 26, 22, 53, 48, 22, 43, 42,  65, 80, 38, 49, 51, 40, 16],
    [5, 5, 7, 1,0,5, 25, 0,1, 3, 2,0,  3, 10,  8,  1,  4,  8,  3,  9,  1,  2,  6, 13],
    [0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,6,0,0,0,0,0,0,0],
    [0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0],
    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0]])
#定义热图的横纵坐标
xLabel1 = ["0", "1", "2","3", "4", "5", "6","7", "8", "9","10", "11", "12", "13","14", "15","16", "17", "18", "19","20", "21", "22","23"]
yLabel1 = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"]
title1='one day raining one year'
d = draw(xLabel1,yLabel1,heatlist1,title1)

2.参考文献、更多实例

[1] Creating annotated heatmaps — Matplotlib 3.5.3 documentation

[2] ax.imshow(heatlist, cmap=plt.cm.hot_r)这里可以根据需要修改,如下:

参数cmap为hot_r,其中_r的意思是就是按照颜色越深,数值越大,如果想数值越大,颜色越浅,只需要去掉_r,直接为hot就行。

hot 从黑平滑过度到红、橙色和黄色的背景色,然后到白色。

cool 包含青绿色和品红色的阴影色。从青绿色平滑变化到品红色。

gray 返回线性灰度色图。

bone 具有较高的蓝色成分的灰度色图。该色图用于对灰度图添加电子的视图。

white 全白的单色色图。

spring 包含品红和黄的阴影颜色。

summer 包含绿和黄的阴影颜色。

autumn 从红色平滑变化到橙色,然后到黄色。

winter 包含蓝和绿的阴影色。

阅读原文
阅读 3166
123 显示电脑版