Python 绘制热图
1.matplitlib绘制热图
1 import random 2 from matplotlib import pyplot as plt 3 from matplotlib import cm 4 from matplotlib import axes 5 6 def draw(): 7 # define the x and y axis of the hotmap 8 xLabel = ['A', 'B', 'C', 'D', 'E'] 9 yLabel = ['1', '2', '3', '4', '5'] 10 11 # prepaer the data, generate the two-dimension data 12 data = [] 13 for i in range(5): 14 temp = [] 15 for j in range(5): 16 k = random.randint(0,100) 17 temp.append(k) 18 data.append(temp) 19 20 # plot the figure 21 fig = plt.figure() 22 ax = fig.add_subplot(111) 23 # define the scale 24 ax.set_yticks(range(len(yLabel))) 25 ax.set_yticklabels(yLabel, fontproperties=plt.cm.hot_r) 26 ax.set_xticks(range(len(xLabel))) 27 ax.set_xtickslabels(xLabel) 28 # make the figure and select the style of hotmap 29 im = ax.imshow(data, cmap = plt.cm.hot_r) # the value is more high, the color is more deep 30 # im = ax.imshow(data, cmap = plt.cm.hot) # the value is more high, the color is more shallow 31 # plt.cm.~ hot, cool, gray, bone, white, spring, summer, autumn, winter 32 33 # add the scale bar of the right site 34 plt.colorbar(im) 35 36 plt.title("This is a title") 37 plt.show() 38 39 d = draw()
2.Seaborn绘制热图
import numpy as np import seaborn as sns import matplotlib.pyplot as plt sns.set() # data 1 np.random.seed(0) uniform_data = np.random.rand(10, 12, vmin = 0, vmax = 1, center = 0) # vmin=0, vmax=1 : the scope of colorbar value # center=0 : colorbar valuee centered at 0 ax = sns.heatmap(uniform_data) # data 2 flights_long = sns.load_dataset("flights") flights = flights_long.pivot("month", "year", "passengers") f, ax = plt.subplots(figsize = (9, 6)) # annot = True: show the value sns.heatmap(flights, annot = True, fmt = 'd', cmap = 'Y|GnBu', linewidth = 5, ax = ax) 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://www.jianshu.com/p/d105d934d876