[seaborn] seaborn学习笔记6-热图HEATMAPPLOT

6 热图Heatmapplot

(代码下载)
热图是指通过将矩阵单个的值表示为颜色的图形表示。热力图显示数值数据的一般视图非常有用,制作热图很简单,且不需要提取特定数据点。在seaborn中使用heatmap函数绘制热力图,此外我们也使用clustermap函数绘制树状图与热图。该章节主要内容有:

  1. 基础热图绘制 Basic Heatmap plot
  2. 热图外观设定 Customize seaborn heatmap
  3. 热图上使用标准化 Use normalization on heatmap
  4. 树状图与热图 Dendrogram with heatmap
# library 导入库
import seaborn as sns
import pandas as pd
import numpy as np
# jupyter notebook显示多行输出
from IPython.core.interactiveshell import InteractiveShell 
InteractiveShell.ast_node_interactivity = 'all'

1. 基础热图绘制 Basic Heatmap plot

  • 普通热图 Basic Heatmap
  • 相关矩阵热图 Correlation matrix
  • 相关矩阵半热图 an half heatmap of correlation matrix
  • 多数据热力图制作 Basic Heatmap of long format data
# 普通热图 Basic Heatmap
# Create a dataset (fake) 制作5行5列的矩阵
df = pd.DataFrame(np.random.random((5,5)), columns=["a","b","c","d","e"])
# 显示数据
df
# Default heatmap: just a visualization of this square matrix 默认热力图
p1 = sns.heatmap(df)
abcde
00.2603190.7496650.5348370.0775990.645868
10.4552600.0889540.8762010.4680240.679460
20.4220900.0298970.6524910.4925160.112680
30.0166690.9791610.2745470.0934390.965549
40.0391590.8518140.7941670.7968550.109723

png

# 相关矩阵热图 Correlation matrix
# 一个常见的任务是检查某些变量是否相关可以轻松计算每对变量之间的相关性,并将其绘制为热图,发现哪个变量彼此相关。
# Create a dataset (fake) 创建数据
df = pd.DataFrame(np.random.random((100,5)), columns=["a","b","c","d","e"])
df.head()
# Calculate correlation between each pair of variable 计算相关系数
corr_matrix=df.corr()
# 显示相关系数结果
corr_matrix
# plot it 绘图 cmap设定颜色版
sns.heatmap(corr_matrix, cmap='PuOr')
abcde
00.4474920.0832330.0543780.5282460.839064
10.9666190.7180030.5844440.4543530.319515
20.1659380.5006610.2210500.3041510.470321
30.0128190.2060020.3172960.9989020.546637
40.1681060.9359170.0812340.6521180.988459
abcde
a1.0000000.0629980.2198050.0958330.160799
b0.0629981.0000000.1730220.040480-0.101984
c0.2198050.1730221.000000-0.049702-0.066863
d0.0958330.040480-0.0497021.0000000.179716
e0.160799-0.101984-0.0668630.1797161.000000
<matplotlib.axes._subplots.AxesSubplot at 0x17a4cc715c0>

png

# 相关矩阵半热图 an half heatmap of correlation matrix
# Create a dataset (fake) 建立数据
df = pd.DataFrame(np.random.random((100,5)), columns=["a","b","c","d","e"])
# Calculate correlation between each pair of variable 计算相关系数
corr_matrix=df.corr()
# Can be great to plot only a half matrix 创建一个corr_matrix等大的O矩阵
mask = np.zeros_like(corr_matrix)
# np.triu_indices_from(mask)返回矩阵上三角形的索引
indices=np.triu_indices_from(mask)
# 显示索引结果
indices
mask[np.triu_indices_from(mask)] = True
with sns.axes_style("white"):
    # mask设置具有缺失值的单元格将自动被屏蔽;square使每个单元格为正方形
    p2 = sns.heatmap(corr_matrix, mask=mask, square=True)
(array([0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 3, 3, 4], dtype=int64),
 array([0, 1, 2, 3, 4, 1, 2, 3, 4, 2, 3, 4, 3, 4, 4], dtype=int64))

png

# 多数据热力图制作 Basic Heatmap of long format data
# 创建两个函数列表
people=np.repeat(("A","B","C","D","E"),5)
feature=list(range(1,6))*5
value=np.random.random(25)
# 创建表格
df=pd.DataFrame({'feature': feature, 'people': people, 'value': value })
 
# plot it 创建透视表
df_wide=df.pivot_table( index='people', columns='feature', values='value' )
p2=sns.heatmap( df_wide, square=True)

png

2. 热图外观设定 Customize seaborn heatmap

  • 单元格值的显示 Annotate each cell with value
  • 自定义网格线 Custom grid lines
  • 轴的显示 Remove X or Y labels
  • 标签隐藏 Hide a few axis labels to avoid overlapping
  • 颜色条坐标显示范围设置 Coordinate range setting of color bar
# Create a dataset (fake)
df = pd.DataFrame(np.random.random((10,10)), columns=["a","b","c","d","e","f","g","h","i","j"])
# annot_kws设置各个单元格中的值,size设定大小
sns.heatmap(df, annot=True, annot_kws={"size": 7});

png

# 自定义网格线 Custom grid lines
sns.heatmap(df, linewidths=2, linecolor='yellow');

png

# 轴的显示 Remove X or Y labels
# 由xticklables和yticklabels控制坐标轴,cbar控制颜色条的显示
sns.heatmap(df, yticklabels=False, cbar=False);

png

# 标签隐藏 Hide a few axis labels to avoid overlapping
# xticklabels表示标签index为该值倍数时显示
sns.heatmap(df, xticklabels=3);

png

# 颜色条坐标显示范围设置 Coordinate range setting of color bar
sns.heatmap(df, vmin=0, vmax=0.5);

png

3. 热图上使用标准化 Use normalization on heatmap

  • 列的规范化 Column normalization
  • 行的规范化 Row normalization
# 列的规范化 Column normalization
# 有时矩阵某一列值远远高于其他列的值,导致整体热图各点颜色趋于两级,需要对列的数据进行规范化的
# Create a dataframe where the average value of the second column is higher:
df = pd.DataFrame(np.random.randn(10,10) * 4 + 3)
# 使得第一列数据明显大于其他列
df[1]=df[1]+40
# If we do a heatmap, we just observe that a column as higher values than others: 没有规范化的热力图
sns.heatmap(df, cmap='viridis');

png

# Now if we normalize it by column 规范化列
df_norm_col=(df-df.mean())/df.std()
sns.heatmap(df_norm_col, cmap='viridis');

png

# 行的规范化 Row normalization  
# 列的规范化相同的原理适用于行规范化。
# Create a dataframe where the average value of the second row is higher
df = pd.DataFrame(np.random.randn(10,10) * 4 + 3)
df.iloc[2]=df.iloc[2]+40
 
# If we do a heatmap, we just observe that a row has higher values than others: 第2行的数据明显大于其他行
sns.heatmap(df, cmap='viridis');

png

# 1: substract mean 行的规范化
df_norm_row=df.sub(df.mean(axis=1), axis=0)
# 2: divide by standard dev
df_norm_row=df_norm_row.div( df.std(axis=1), axis=0 )
# And see the result
sns.heatmap(df_norm_row, cmap='viridis');

png

4. 树状图与热图 Dendrogram with heatmap

  • 基础树状图与热图绘制 Dendrogram with heat map and coloured leaves
  • 树形图与热图规范化 normalize of Dendrogram with heatmap
  • 树形图与热图距离参数设定 distance of Dendrogram with
  • 树形图与热图聚类方法参数设定 cluster method of Dendrogram with heatmap
  • 图像颜色设定 Change color palette
  • 离群值设置 outliers set

树状图就是层次聚类的表现形式。层次聚类的合并算法通过计算两类数据点间的相似性,对所有数据点中最为相似的两个数据点进行组合,并反复迭代这一过程。简单的说层次聚类的合并算法是通过计算每一个类别的数据点与所有数据点之间的距离来确定它们之间的相似性,距离越小,相似度越高。并将距离最近的两个数据点或类别进行组合,生成聚类树。在树状图中通过线条连接表示两类数据的距离。

# 基础树状图与热图绘制 Dendrogram with heat map and coloured leaves
from matplotlib import pyplot as plt
import pandas as pd

# 使用mtcars数据集,通过一些数字变量提供几辆汽车的性能参数。 
# Data set mtcars数据集 下载
#url = 'https://python-graph-gallery.com/wp-content/uploads/mtcars.csv'
# 原链接已经失效,感谢[Yunxu_Li]https://blog.csdn.net/qq_37735698提供链接
url ='https://gist.github.com/seankross/a412dfbd88b3db70b74b/#file-mtcars-csv'
df = pd.read_csv(url)
df = df.set_index('model')
# 横轴为汽车性能参数,纵轴为汽车型号
df.head()
mpgcyldisphpdratwtqsecvsamgearcarb
model
Mazda RX421.06160.01103.902.62016.460144
Mazda RX4 Wag21.06160.01103.902.87517.020144
Datsun 71022.84108.0933.852.32018.611141
Hornet 4 Drive21.46258.01103.083.21519.441031
Hornet Sportabout18.78360.01753.153.44017.020032
# Prepare a vector of color mapped to the 'cyl' column
# 设定发动机汽缸数6,4,,8指示不同的颜色
my_palette = dict(zip(df.cyl.unique(), ["orange","yellow","brown"]))
my_palette
# 列出不同汽车的发动机汽缸数
row_colors = df.cyl.map(my_palette)
row_colors
# metric数据度量方法, method计算聚类的方法
# standard_scale标准维度(0:行或1:列即每行或每列的含义,减去最小值并将每个维度除以其最大值)
sns.clustermap(df, metric="correlation", method="single", cmap="Blues", standard_scale=1, row_colors=row_colors)
{6: 'orange', 4: 'yellow', 8: 'brown'}






model
Mazda RX4              orange
Mazda RX4 Wag          orange
Datsun 710             yellow
Hornet 4 Drive         orange
Hornet Sportabout       brown
Valiant                orange
Duster 360              brown
Merc 240D              yellow
Merc 230               yellow
Merc 280               orange
Merc 280C              orange
Merc 450SE              brown
Merc 450SL              brown
Merc 450SLC             brown
Cadillac Fleetwood      brown
Lincoln Continental     brown
Chrysler Imperial       brown
Fiat 128               yellow
Honda Civic            yellow
Toyota Corolla         yellow
Toyota Corona          yellow
Dodge Challenger        brown
AMC Javelin             brown
Camaro Z28              brown
Pontiac Firebird        brown
Fiat X1-9              yellow
Porsche 914-2          yellow
Lotus Europa           yellow
Ford Pantera L          brown
Ferrari Dino           orange
Maserati Bora           brown
Volvo 142E             yellow
Name: cyl, dtype: object






<seaborn.matrix.ClusterGrid at 0x17a4e048da0>

png

# 树形图与热图规范化 normalize of Dendrogram with heatmap
# Standardize or Normalize every column in the figure
# Standardize 标准化
sns.clustermap(df, standard_scale=1)
# Normalize 正则化
sns.clustermap(df, z_score=1)
<seaborn.matrix.ClusterGrid at 0x17a4e0266d8>






<seaborn.matrix.ClusterGrid at 0x17a4e0e3fd0>

png

png

# 树形图与热图距离参数设定 distance of Dendrogram with heatmap
# 相似性
sns.clustermap(df, metric="correlation", standard_scale=1)
# 欧几里得距离
sns.clustermap(df, metric="euclidean", standard_scale=1)
<seaborn.matrix.ClusterGrid at 0x17a4dfd6588>






<seaborn.matrix.ClusterGrid at 0x17a4de86048>

png

png

# 树形图与热图聚类方法参数设定 cluster method of Dendrogram with heatmap
# single-linkage算法
sns.clustermap(df, metric="euclidean", standard_scale=1, method="single")
# 聚类分析法ward,推荐使用
sns.clustermap(df, metric="euclidean", standard_scale=1, method="ward")
<seaborn.matrix.ClusterGrid at 0x17a4df7dc88>






<seaborn.matrix.ClusterGrid at 0x17a4f550f98>

png

png

# 图像颜色设定 Change color palette 
sns.clustermap(df, metric="euclidean", standard_scale=1, method="ward", cmap="mako")
sns.clustermap(df, metric="euclidean", standard_scale=1, method="ward", cmap="viridis")
<seaborn.matrix.ClusterGrid at 0x17a4e298f98>






<seaborn.matrix.ClusterGrid at 0x17a4e298748>

png

png

# 离群值设置 outliers set
# Ignore outliers
# Let's create an outlier in the dataset, 添加离群值
df.iloc[15,5] = 1000
# use the outlier detection 计算时忽略离群值
sns.clustermap(df, robust=True)
# do not use it 不忽略离群值
sns.clustermap(df, robust=False)
<seaborn.matrix.ClusterGrid at 0x17a4ff99a58>






<seaborn.matrix.ClusterGrid at 0x17a4f943278>

png

png

  • 8
    点赞
  • 60
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值