利用python画热力图

heatmap图可直观地展示相关性分析的结果,而且比较美观。

前期准备

数据导入

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

data= pd.read_excel('data.xlsx')
#print(data)

数据重整

data0=data.iloc[:, 72:81]
#data0
data1=data.iloc[:, 1:38]
data1=pd.merge(data1,data0,how='outer', left_index=True, right_index=True)

展示列名

column = data1.columns.tolist()[1:]
print(column)

相关性分析

计算相关系数

mcorr1 = data1.corr()
mcorr_data1 = np.array(mcorr1.结算价)
print(mcorr_data1)

画热力图

需要用到seaborn库

import seaborn as sns
mask1 = np.zeros_like(mcorr1, dtype=np.bool)  # 构造与mcorr同维矩阵 为bool型
mask1[np.triu_indices_from(mask1)] = True  # 角分线右侧为True
# 绘制图像
plt.figure(figsize=(40, 40))
sns.set(font="simhei")#遇到标签需要汉字的可以在绘图前加上这句
cmap1 = sns.diverging_palette(240, 10, n=9)  # 返回matplotlib colormap对象
g = sns.heatmap(mcorr1, mask=mask1, cmap=cmap1, square=True, annot=True, fmt='0.2f')  # 热力图
plt.show()

seaborn.diverging_palette参数设置:seaborn.diverging_palette(h_neg, h_pos, s=75, l=50, sep=10, n=6, center='light', as_cmap=False)

在两个 HUSL 颜色直接建立一个发散调色板。

如果使用 IPython notebook,还可以通过 choose_diverging_palette() 函数交互式选择调色板。

参数:h_neg, h_pos:float in [0, 359]

图的正负范围的锚定色调

s:[0, 100] 范围内的浮点数,可选

图的两个范围的锚定饱和度

l:[0, 100] 范围内的浮点数,可选

图的两个范围的锚定亮度

n:int,可选

调色板中的颜色数(如果为not,返回一个colormap)

center:{“light”, “dark”}, 可选

调色板中心为亮或暗

as_cmap:bool, 可选

如果为 true,返回一个 matplotlib colormap 而不是一个颜色列表。

返回值:palette or cmap:seaborn color palette or matplotlib colormap

类似列表的颜色对象的 RGB 元组,或者可以将连续值映射到颜色的 colormap 对象,具体取决于 as_cmap 参数的值。

更多细节可参考Seaborn 0.9 中文文档:seaborn.diverging_palette

作者: 公子小白

SOS团团员,非外星人、未来人、超能力者。。。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注