Python数据分析之Seaborn(热图绘制)

时间:2022-07-22
本文章向大家介绍Python数据分析之Seaborn(热图绘制),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Seaborn热图绘制

%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np;
np.random.seed(0)
import seaborn as sns;
sns.set()

热图基础

seaborn.heatmap(data, vmin=None, vmax=None, cmap=None, center=None, robust=False, annot=None, fmt='.2g', annotkws=None, linewidths=0, linecolor='white', cbar=True, cbarkws=None, cbar_ax=None, square=False, ax=None, xticklabels=True, yticklabels=True, mask=None, **kwargs)
  • data:矩阵数据集,可以使numpy的数组(array),如果是pandas的dataframe,则df的index/column信息会分别对应到heatmap的columns和rows
  • linewidths,热力图矩阵之间的间隔大小
  • vmax,vmin, 图例中最大值和最小值的显示值,没有该参数时默认不显示
  • cmap:matplotlib的colormap名称或颜色对象;如果没有提供,默认为cubehelix map (数据集为连续数据集时) 或 RdBu_r (数据集为离散数据集时)
  • center:将数据设置为图例中的均值数据,即图例中心的数据值;通过设置center值,可以调整生成的图像颜色的整体深浅;设置center数据时,如果有数据溢出,则手动设置的vmax、vmin会自动改变
  • xticklabels: 如果是True,则绘制dataframe的列名。如果是False,则不绘制列名。如果是列表,则绘制列表中的内容作为xticklabels。 如果是整数n,则绘制列名,但每个n绘制一个label。 默认为True。
  • yticklabels: 如果是True,则绘制dataframe的行名。如果是False,则不绘制行名。如果是列表,则绘制列表中的内容作为yticklabels。 如果是整数n,则绘制列名,但每个n绘制一个label。 默认为True。默认为True。
  • annotate的缩写,annot默认为False,当annot为True时,在heatmap中每个方格写入数据
  • annot_kws,当annot为True时,可设置各个参数,包括大小,颜色,加粗,斜体字等
  • fmt,格式设置
uniform_data = np.random.rand(3, 3) #生成数据
print (uniform_data)
heatmap = sns.heatmap(uniform_data) # 生成热力图
[[ 0.64272796  0.0229858   0.21897478]
 [ 0.41076627  0.28860677  0.94805105]
 [ 0.96513582  0.57781451  0.96400349]]
# 改变颜色映射的值范围
ax = sns.heatmap(uniform_data, vmin=0.2, vmax=1)
#为以0为中心的数据绘制一张热图
ax = sns.heatmap(uniform_data, center=0)

案例分析

flights = sns.load_dataset("flights") #加载航班数据集
flights.head() #显示部分数据
flights = flights.pivot("month", "year", "passengers") #修改数据排列
flights.head()
ax = sns.heatmap(flights) #绘制热图
ax = sns.heatmap(flights, annot=True,fmt="d") #在heatmap中每个方格写入数据,按照整数形式
ax = sns.heatmap(flights, linewidths=.5) #热力图矩阵之间的间隔大小
ax = sns.heatmap(flights, cmap="YlGnBu") #修改热图颜色
ax = sns.heatmap(flights, cbar=False) #不显示热图图例

参考

[Style functions]http://seaborn.pydata.org/tutorial/aesthetics.html#aesthetics-tutorial

[Color palettes]http://seaborn.pydata.org/tutorial/color_palettes.html#palette-tutorial

[Distribution plots]http://seaborn.pydata.org/tutorial/distributions.html#distribution-tutorial

[Categorical plots]http://seaborn.pydata.org/tutorial/categorical.html#categorical-tutorial

[Regression plots]http://seaborn.pydata.org/tutorial/regression.html#regression-tutorial

[Axis grid objects]http://seaborn.pydata.org/tutorial/axis_grids.html#grid-tutorial [10分钟python图表绘制]https://zhuanlan.zhihu.com/p/24464836