前言

在日常工作中,经常可以见到各种各种精美的热力图,热力图的应用非常广泛,下面一起来学习下Python的Seaborn库中热力图(heatmap)如何来进行使用。

本次运行的环境为:

  • windows 64位系统

  • python 3.5

  • jupyter notebook

1 构造数据

  1. import seaborn as sns
  2. import pandas as pd
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. % matplotlib inline
  1. region = ['Albania', 'Algeria', 'Angola', 'Argentina', 'Armenia', 'Azerbaijan',
  2. 'Bahamas', 'Bangladesh', 'Belize', 'Bhutan', 'Bolivia',
  3. 'Bosnia and Herzegovina', 'Brazil', 'Burkina Faso', 'Burundi',
  4. 'Cambodia', 'Cameroon', 'Cape Verde', 'Chile', 'China', 'Colombia',
  5. 'Costa Rica', 'Cote d Ivoire', 'Cuba', 'Cyprus',
  6. "Democratic People's Republic of Korea",
  7. 'Democratic Republic of the Congo', 'Dominican Republic', 'Ecuador',
  8. 'Egypt', 'El Salvador', 'Equatorial Guinea', 'Ethiopia', 'Fiji',
  9. 'Gambia', 'Georgia', 'Ghana', 'Guatemala', 'Guyana', 'Honduras']
  10. kind = ['Afforestation & reforestation', 'Biofuels', 'Biogas',
  11. 'Biomass', 'Cement', 'Energy efficiency', 'Fuel switch',
  12. 'HFC reduction/avoidance', 'Hydro power',
  13. 'Leak reduction', 'Material use', 'Methane avoidance',
  14. 'N2O decomposition', 'Other renewable energies',
  15. 'PFC reduction and substitution','PV',
  16. 'SF6 replacement', 'Transportation', 'Waste gas/heat utilization',
  17. 'Wind power']
  1. print(len(region))
  2. print(len(kind))
  1. 40
  2. 20
  1. np.random.seed(100)
  2. arr_region = np.random.choice(region, size=(10000,))
  3. list_region = list(arr_region)
  4. arr_kind = np.random.choice(kind, size=(10000,))
  5. list_kind = list(arr_kind)
  6. values = np.random.randint(50, 1000, 10000)
  7. list_values = list(values)
  8. df = pd.DataFrame({'region':list_region,
  9. 'kind': list_kind,
  10. 'values':list_values})
  11. df.head()

  1. pt = df.pivot_table(index='kind', columns='region', values='values', aggfunc=np.sum)
  2. pt.head()

  1. f, ax = plt.subplots(figsize = (10, 4))
  2. cmap = sns.cubehelix_palette(start = 1, rot = 3, gamma=0.8, as_cmap = True)
  3. sns.heatmap(pt, cmap = cmap, linewidths = 0.05, ax = ax)
  4. ax.set_title('Amounts per kind and region')
  5. ax.set_xlabel('region')
  6. ax.set_ylabel('kind')
  7. f.savefig('sns_heatmap_normal.jpg', bbox_inches='tight')
  8. # ax.set_xticklabels(ax.get_xticklabels(), rotation=-90)

2 Seaborn的heatmap各个参数介绍

seaborn.heatmap

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, ax=None, xticklabels=True, yticklabels=True, mask=None, **kwargs)

  • data:矩阵数据集,可以使numpy的数组(array),如果是pandas的dataframe,则df的index/column信息会分别对应到heatmap的columns和rows
  • linewidths,热力图矩阵之间的间隔大小
  • vmax,vmin, 图例中最大值和最小值的显示值,没有该参数时默认不显示

2.1 cmap

  • cmap:matplotlib的colormap名称或颜色对象;如果没有提供,默认为cubehelix map (数据集为连续数据集时) 或 RdBu_r (数据集为离散数据集时)
  1. f, (ax1,ax2) = plt.subplots(figsize = (10, 8),nrows=2)
  2. # cubehelix map颜色
  3. cmap = sns.cubehelix_palette(start = 1.5, rot = 3, gamma=0.8, as_cmap = True)
  4. sns.heatmap(pt, linewidths = 0.05, ax = ax1, vmax=15000, vmin=0, cmap=cmap)
  5. ax1.set_title('cubehelix map')
  6. ax1.set_xlabel('')
  7. ax1.set_xticklabels([]) #设置x轴图例为空值
  8. ax1.set_ylabel('kind')
  9. # matplotlib colormap
  10. sns.heatmap(pt, linewidths = 0.05, ax = ax2, vmax=15000, vmin=0, cmap='rainbow')
  11. # rainbow为 matplotlib 的colormap名称
  12. ax2.set_title('matplotlib colormap')
  13. ax2.set_xlabel('region')
  14. ax2.set_ylabel('kind')
  15. f.savefig('sns_heatmap_cmap.jpg', bbox_inches='tight')

2.2 center

  • center:将数据设置为图例中的均值数据,即图例中心的数据值;通过设置center值,可以调整生成的图像颜色的整体深浅;设置center数据时,如果有数据溢出,则手动设置的vmax、vmin会自动改变
  1. f, (ax1,ax2) = plt.subplots(figsize = (10, 8),nrows=2)
  2. cmap = sns.cubehelix_palette(start = 1.5, rot = 3, gamma=0.8, as_cmap = True)
  3. sns.heatmap(pt, linewidths = 0.05, ax = ax1, vmax=15000, vmin=0, cmap=cmap, center=None )
  4. # center为None时,由于最小值为0,最大值为15000,相当于center值为vamx和vmin的均值,即7500
  5. ax1.set_title('center=None')
  6. ax1.set_xlabel('')
  7. ax1.set_xticklabels([]) #设置x轴图例为空值
  8. ax1.set_ylabel('kind')
  9. sns.heatmap(pt, linewidths = 0.05, ax = ax2, vmax=15000, vmin=0, cmap=cmap, center=3000 )
  10. # 由于均值为2000,当center设置为3000时,大部分数据会比7500大,所以center=3000时,生成的图片颜色要深
  11. # 设置center数据时,如果有数据溢出,则手动设置的vmax或vmin会自动改变
  12. ax2.set_title('center=3000')
  13. ax2.set_xlabel('region')
  14. ax2.set_ylabel('kind')
  15. f.savefig('sns_heatmap_center.jpg', bbox_inches='tight')

2.3 robust

  1. f, (ax1,ax2) = plt.subplots(figsize = (10, 8),nrows=2)
  2. cmap = sns.cubehelix_palette(start = 1.5, rot = 3, gamma=0.8, as_cmap = True)
  3. sns.heatmap(pt, linewidths = 0.05, ax = ax1, cmap=cmap, center=None, robust=False )
  4. # robust默认为False
  5. ax1.set_title('robust=False')
  6. ax1.set_xlabel('')
  7. ax1.set_xticklabels([]) #设置x轴图例为空值
  8. ax1.set_ylabel('kind')
  9. sns.heatmap(pt, linewidths = 0.05, ax = ax2, cmap=cmap, center=None, robust=True )
  10. # If True and vmin or vmax are absent, the colormap range is computed with robust quantiles instead of the extreme values.
  11. ax2.set_title('robust=True')
  12. ax2.set_xlabel('region')
  13. ax2.set_ylabel('kind')
  14. f.savefig('sns_heatmap_robust.jpg', bbox_inches='tight')

2.4 mask

  1. f, (ax1,ax2) = plt.subplots(figsize = (10, 8),nrows=2)
  2. cmap = sns.cubehelix_palette(start = 1.5, rot = 3, gamma=0.8, as_cmap = True)
  3. p1 = sns.heatmap(pt, linewidths = 0.05,ax=ax1, vmax=15000, vmin=0, cmap=cmap, center=None, robust=False, mask=None )
  4. # robust默认为False
  5. ax1.set_title('mask=None')
  6. ax1.set_xlabel('')
  7. ax1.set_xticklabels([]) #设置x轴图例为空值
  8. ax1.set_ylabel('kind')
  9. p2 = sns.heatmap(pt, linewidths = 0.05, ax=ax2, vmax=15000, vmin=0, cmap=cmap, center=None, robust=False, annot=False,mask=pt<10000 )
  10. # mask: boolean array or DataFrame
  11. ax2.set_title('mask: boolean DataFrame')
  12. ax2.set_xlabel('region')
  13. ax2.set_ylabel('kind')
  14. f.savefig('sns_heatmap_mask.jpg', bbox_inches='tight')

2.5 xticklabels, yticklabels

  • xticklabels: 如果是True,则绘制dataframe的列名。如果是False,则不绘制列名。如果是列表,则绘制列表中的内容作为xticklabels。 如果是整数n,则绘制列名,但每个n绘制一个label。 默认为True。
  • yticklabels: 如果是True,则绘制dataframe的行名。如果是False,则不绘制行名。如果是列表,则绘制列表中的内容作为yticklabels。 如果是整数n,则绘制列名,但每个n绘制一个label。 默认为True。默认为True。
  1. f, (ax1,ax2) = plt.subplots(figsize = (10, 8),nrows=2)
  2. cmap = sns.cubehelix_palette(start = 1.5, rot = 3, gamma=0.8, as_cmap = True)
  3. p1 = sns.heatmap(pt, linewidths = 0.05,ax=ax1, vmax=15000, vmin=0, cmap=cmap, center=None, robust=False, mask=None, xticklabels=False )
  4. # robust默认为False
  5. ax1.set_title('xticklabels=None')
  6. ax1.set_xlabel('')
  7. # ax1.set_xticklabels([]) #设置x轴图例为空值
  8. ax1.set_ylabel('kind')
  9. p2 = sns.heatmap(pt, linewidths = 0.05, ax=ax2, vmax=15000, vmin=0, cmap=cmap, center=None, robust=False, annot=False,mask=None,xticklabels=3, yticklabels=list(range(20)) )
  10. # mask: boolean array or DataFrame
  11. ax2.set_title('xticklabels=3, yticklabels is a list')
  12. ax2.set_xlabel('region')
  13. ax2.set_ylabel('kind')
  14. f.savefig('sns_heatmap_xyticklabels.jpg', bbox_inches='tight')

2.6 annot

  • annotate的缩写,annot默认为False,当annot为True时,在heatmap中每个方格写入数据
  • annot_kws,当annot为True时,可设置各个参数,包括大小,颜色,加粗,斜体字等
  1. np.random.seed(0)
  2. x = np.random.randn(10, 10)
  3. f, (ax1, ax2) = plt.subplots(figsize=(8,8),nrows=2)
  4. sns.heatmap(x, annot=True, ax=ax1)
  5. sns.heatmap(x, annot=True, ax=ax2, annot_kws={'size':9,'weight':'bold', 'color':'blue'})
  6. # Keyword arguments for ax.text when annot is True.
  7. # http://stackoverflow.com/questions/35024475/seaborn-heatmap-key-words
  8. f.savefig('sns_heatmap_annot.jpg')

**关于annot_kws的设置,还有很多值得研究的地方,ax.text有很多属性,有兴趣的可以去研究下;

ax.text可参考官方文档:http://matplotlib.org/api/text_api.html#matplotlib.text.Text

2.7 fmt

  • fmt,格式设置
  1. np.random.seed(0)
  2. x = np.random.randn(10, 10)
  3. f, (ax1, ax2) = plt.subplots(figsize=(8,8),nrows=2)
  4. sns.heatmap(x, annot=True, ax=ax1)
  5. sns.heatmap(x, annot=True, fmt='.1f', ax=ax2)
  6. f.savefig('sns_heatmap_fmt.jpg')

3 案例应用:突出显示某些数据

3.1 method 1:利用mask来实现

  1. f,ax=plt.subplots(figsize=(10,5))
  2. x = np.random.randn(10, 10)
  3. sns.heatmap(x, annot=True, ax=ax)
  4. sns.heatmap(x, mask=x < 1, cbar=False, ax=ax,
  5. annot=True, annot_kws={"weight": "bold"})
  6. f.savefig('sns_heatmap_eg1.jpg')

3.2 method 2:利用ax.texts来实现

  1. f,ax=plt.subplots(figsize=(10,5))
  2. flights = sns.load_dataset("flights")
  3. flights = flights.pivot("month", "year", "passengers")
  4. pic = sns.heatmap(flights, annot=True, fmt="d", ax=ax)
  5. for text in pic.texts:
  6. text.set_size(8)
  7. if text.get_text() == '118':
  8. text.set_size(12)
  9. text.set_weight('bold')
  10. text.set_style('italic')
  11. f.savefig('sns_heatmap_eg2.jpg')

你可能会发现本文中seaborn的heatmap中还有些参数没有进行介绍,介于篇幅,这里就不在啰嗦了,建议各位小伙伴自己可以研究下其他参数如何使用。

如需转载,请在公众号留言进行授权事宜沟通。

转载请注明文章来自微信公众号“Python数据之道”。

更多精彩内容请关注微信公众号:

“Python数据之道”

Python可视化:Seaborn库热力图使用进阶的更多相关文章

  1. Python数据可视化-seaborn库之countplot

    在Python数据可视化中,seaborn较好的提供了图形的一些可视化功效. seaborn官方文档见链接:http://seaborn.pydata.org/api.html countplot是s ...

  2. Python可视化TVTK库初使用

    本周学习了初步的TVTK库的安装及使用方法,第一次通过tvtk.CubeSource方法建立了一个长方体对象.对TVTK的接触有了新的体会. 首先,在网上下载了以下五个库并按顺序通过pip指令在cmd ...

  3. Python可视化 | Seaborn包—heatmap()

    seaborn.heatmap()的参数 seaborn.heatmap(data, vmin=None, vmax=None, cmap=None, center=None, robust=Fals ...

  4. Python可视化 | Seaborn包—kdeplot和distplot

    import pandas as pd import numpy as np import seaborn as sns import matplotlib import matplotlib.pyp ...

  5. Pycon 2017: Python可视化库大全

    本文首发于微信公众号“Python数据之道” 前言 本文主要摘录自 pycon 2017大会的一个演讲,同时结合自己的一些理解. pycon 2017的相关演讲主题是“The Python Visua ...

  6. Python可视化库

    转自小小蒲公英原文用Python可视化库 现如今大数据已人尽皆知,但在这个信息大爆炸的时代里,空有海量数据是无实际使用价值,更不要说帮助管理者进行业务决策.那么数据有什么价值呢?用什么样的手段才能把数 ...

  7. Matplotlib和Seaborn演示Python可视化

    数据可视化:就是使用图形图表等方式来呈现数据,图形图表能够高效清晰地表达数据包含的信息. Seaborn是基于matplotlib,在matplotlib的基础上进行了更高级的API封装,便于用户可以 ...

  8. Python可视化库-Matplotlib使用总结

    在做完数据分析后,有时候需要将分析结果一目了然地展示出来,此时便离不开Python可视化工具,Matplotlib是Python中的一个2D绘图工具,是另外一个绘图工具seaborn的基础包 先总结下 ...

  9. python 可视化库

    在做titanic分析的过程中,看了一些大神的想法,发现在分析数据的过程中,许多大神会使用到seaborn,plotly这些库,而我等小白仅仅知道matplotlib这个唯一的数据可视化库而已.上网查 ...

随机推荐

  1. 微信小程序,前端大梦想(二)

    微信小程序的视图与渲染  今天我们从四个方面来了解小程序:   •组件的基本使用  •数据绑定  •渲染标签  •模板的使用     一.组件的基本使用:  微信小程序为我们的开发提供了丰富的UI组件 ...

  2. 概率检索模型及BM25

    概率排序原理 以往的向量空间模型是将query和文档使用向量表示然后计算其内容相似性来进行相关性估计的,而概率检索模型是一种直接对用户需求进行相关性的建模方法,一个query进来,将所有的文档分为两类 ...

  3. redis object 对象系统

    redis object对象系统 概述 redis 当中, sds字符串, adlist双向链表, dict字典, ziplist压缩链表, intset整数集合等均为底层数据结构 redis 并没有 ...

  4. jmeter执行case结果插入DB数据优化

    访问初始实现路径:jmeter执行case结果插入DB生成报表和备份记录 借前面实现导入DB数据先说明之前数据的缺点: 第一,若需要依赖接口的数据,会把依赖接口的case统计进去造成数据统计错误.第二 ...

  5. 记一些让footer始终位于网页底部的方法

    上次说把网页的头部和尾部分离出来作为一个单独的文件,所有网页共用,这样比较方便修改,然而,,,我发现某些方法里尾部会紧跟在头部后面,把内容挤在下面..而且有的页面内容少的话不能把尾部挤到最下面,所以, ...

  6. 阿里云centos 安装和配置 DokuWiki

    安装 1) 添加虚拟主机:由于我的 阿里云CentOs服务器 安装了oneinstack的一键部署PHP.JAVA.Nginx等环境,所以域名配置很方便,照着文档一步一步做就可以了 cd /root/ ...

  7. office web apps 整合Java web项目

    之前两篇文章将服务器安装好了,项目主要的就是这么讲其整合到我们的项目中,网上大部分都是asp.net的,很少有介绍Java如何整合的,经过百度,终于将其整合到了我的项目中. 首先建个servlet拦截 ...

  8. JavaScript 中有关Array操作的一些函数

    JavaScript的Array可以包含任意数据类型,并通过索引来访问每个元素. 要取得Array的长度,直接访问length属性: var arr = [1, 0.222, 'Hi', null, ...

  9. matlab笔记(1) 元胞结构cell2mat和num2cell

    摘自于:https://zhidao.baidu.com/question/1987862234171281467.html https://www.zybang.com/question/dcb09 ...

  10. elasticsearch系列(二) esrally压测

    环境准备 linux centOS(工作环境) python3.4及以上 pip3 JDK8 git1.9及以上 gradle2.13级以上 准备过程中的坑 这些环境准备没什么太大问题,都是wget下 ...