文章目录
- 计算相关系数矩阵
- seaborn库画热力图的参数详解
- seaborn 库画热力图的例子
-
- 利用numpy array简单的画一个热力图:data
- 指定颜色的数值范围:vmax,vmin
- 确定颜色映射的中心:center
- 利用pandas dataframe画一个有实际意义的行列标签
- python 制图显示中文字符
- 直接读取csv,画热力图
- 在矩阵色块中添加注释:annot,fmt,annot_kws
- 在色块间添加分割线和指定分割线宽度和颜色:linewidths,linecolor
- 改变行列标签:xticklables,yticklables
- 改变色带:cmap
- 指定色带的中心值:center
- 色带具体设置:cbar,cbar_kws,cbar_ax
- 掩膜部分图像:mask
- 设置坐标字体、方向
计算相关系数矩阵
- 为防止乱码,添加utf-8和unicode_escape,并在中文路径处指定gbk编码格式
# coding : utf-8
# coding : unicode-escape
- 导入各种库
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn
- 利用numpy的corrcoef计算相关矩阵
# np.corrcoef(a)可计算行与行之间的相关系数
# np.corrcoef(a,rowvar=0)用于计算列与列之间的相关系数
a=np.array([[1, 1, 2, 2, 3],
[2, 2, 3, 3, 5],
[1, 4, 2, 2, 3]])
print("a is :","\n",a)
r1 = np.corrcoef(a) # 按行算相关系数
r2 = np.corrcoef(a,rowvar=0) # 按列算相关系数
print("r1 is :","\n",r1)
print("r2 is :","\n",r2)
# 应用公式0.5*value+0.5可以将相关系数矩阵的值域由[-1,1]映射为[0,1]
r3 = r2*0.5+0.5
print("r3 is :","\n",r3)
结果如下:
seaborn库画热力图的参数详解
参考官方API参数及地址:
seaborn.heatmap(data, vmin=None, vmax=None, cmap=None, center=None, robust=False, annot=None, fmt=’.2g’, annot_kws=None, linewidths=0, linecolor=‘white’, cbar=True, cbar_kws=None, cbar_ax=None, square=False, xticklabels=‘auto’, yticklabels=‘auto’, mask=None, ax=None, **kwargs)
seaborn库官方地址
Plot rectangular data as a color-encoded matrix.
以颜色编码矩阵的形式绘制矩阵数据
This is an Axes-level function and will draw the heatmap into the currently-active Axes if none is provided to the ax argument. Part of this Axes space will be taken and used to plot a colormap, unless cbar is False or a separate Axes is provided to cbar_ax.
Parameters:
参数:
-
data : rectangular dataset
- 2D dataset that can be coerced into an ndarray. If a Pandas DataFrame is provided, the index/column information will be used to label the columns and rows.
- 矩阵数据集,可以是numpy的数组(array),也可以是pandas的DataFrame。如果是DataFrame,则df的index/column信息会分别对应到heatmap的columns和rows,即pt.index是热力图的行标,pt.columns是热力图的列标
热力图矩阵块颜色参数:
-
vmin, vmax : floats, optional
- Values to anchor the colormap, otherwise they are inferred from the data and other keyword arguments.
- 可选,分别是热力图的颜色取值最大和最小范围,默认是根据data数据表里的取值确定
-
cmap : matplotlib colormap name or object, or list of colors, optional
- The mapping from data values to color space. If not provided, the default will depend on whether center is set.
- 调色板,取值是matplotlib包里的colormap名称或颜色对象,或者表示颜色的列表;
作用是将数字映射到颜色空间,如果不设置,默认颜色映射将取决于参数center
-
center : float, optional</