使用seaborn绘制漂亮的热度图

本文介绍如何使用Python的Seaborn库绘制热力图,包括基本配置、数据准备及不同应用场景下的参数调整。从简单矩阵到复杂数据集,展示了如何利用热力图进行数据可视化。

还是使用jupyter notebook作为开发环境,首先引入所必须的包以及对环境进行相应设置。

import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
# 调用魔法方法 使得每次显示结果时不用调用plt.show()方法
sns.set(style='whitegrid', color_codes=True)
# 设置默认风格 
np.random.seed(sum(map(ord, 'categorical')))
# 当我们设置相同的seed,每次生成的随机数相同。
# 如果不设置seed,则每次会生成不同的随机数
# map() 会根据提供的函数对指定序列做映射。
# 即返回'distributions'该字符串每个字母的二进制数
# 并用sum函数求和,将和作为种子,这里似乎是习惯上的写法。

首先先产生一组3*3矩阵,并调用sns的heatmap()方法绘制一个简单的热度图。

data = np.random.rand(3, 3)
sns.heatmap(data)

结果如下:
这里写图片描述
可以通过右边的小竖线,看出来该3*3矩阵的数据大概分布规律。

ndata = np.random.randn(3,3)
print(ndata)
sns.heatmap(ndata, center=0)

我们还可以通过center参数设置中间值,结果如下:

[ [-1.61598034 1.2296366 0.82214517]
[-0.39834485 -0.97147653 -0.5531709 ]
[ 0.26034732 -0.03442802 0.96284724] ]

这里写图片描述

载入内置数据集:

flights = sns.load_dataset('flights')
flights.head()

year month passengers
0 1949 January 112
1 1949 February 118
2 1949 March 132
3 1949 April 129
4 1949 May 121

# pivot() 可以将dataframe转换为行列式矩阵 并指定每个元素的存储值
flights = flights.pivot(index='month', columns='year',  values='passengers')
# print(flights)
plt.figure(figsize=(10,6))
ax = sns.heatmap(flights, fmt='d', linewidths=.5)
# fmt设置字体模式  linewidth设置每个小方格的间距 线宽

结果如图:
这里写图片描述
我们还可以设置绘图板的颜色模式:

plt.figure(figsize=(10,6))
ax = sns.heatmap(flights, fmt='d', linewidths=.5, cmap='YlGnBu')

结果如下:
这里写图片描述

heatmap函数具体参数如下:

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.

vmin, vmax : floats, optional 开始与结束的范围 即右边小竖线的范围

Values to anchor the colormap, otherwise they are inferred from the data and other keyword arguments.

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.

center : float, optional

The value at which to center the colormap when plotting divergant data. Using this parameter will change the default cmap if none is specified.

robust : bool, optional

If True and vmin or vmax are absent, the colormap range is computed with robust quantiles instead of the extreme values.

annot : bool or rectangular dataset, optional

If True, write the data value in each cell. If an array-like with the same shape as data, then use this to annotate the heatmap instead of the raw data.

fmt : string, optional

String formatting code to use when adding annotations.

annot_kws : dict of key, value mappings, optional

Keyword arguments for ax.text when annot is True.

linewidths : float, optional

Width of the lines that will divide each cell.

linecolor : color, optional

Color of the lines that will divide each cell.

cbar : boolean, optional

Whether to draw a colorbar.

cbar_kws : dict of key, value mappings, optional

Keyword arguments for fig.colorbar.

cbar_ax : matplotlib Axes, optional

Axes in which to draw the colorbar, otherwise take space from the main Axes.

square : boolean, optional

If True, set the Axes aspect to “equal” so each cell will be square-shaped.

xticklabels, yticklabels : “auto”, bool, list-like, or int, optional

If True, plot the column names of the dataframe. If False, don’t plot the column names. If list-like, plot these alternate labels as the xticklabels. If an integer, use the column names but plot only every n label. If “auto”, try to densely plot non-overlapping labels.

mask : boolean array or DataFrame, optional

If passed, data will not be shown in cells where mask is True. Cells with missing values are automatically masked.

ax : matplotlib Axes, optional

Axes in which to draw the plot, otherwise use the currently-active Axes.

kwargs : other keyword arguments

All other keyword arguments are passed to ax.pcolormesh.
### 使用 Python 创建热度Heatmap热度是一种以颜色形式展示数据矩阵的可视化方法,常用于显示数据集中不同变量之间的相关性、强度或分布情况。在 Python 中,`seaborn` 和 `matplotlib` 是创建热度的主要工具,其中 `seaborn` 提供了更为简洁和美观的接口。 以下是一个使用 `seaborn` 创建热度的完整示例: ```python import seaborn as sns import pandas as pd # 创建一个示例 DataFrame df = pd.DataFrame({ 'col1': [1, 2, 3, 4, 5], 'col2': [1, 2, 3, 4, 5], 'col3': [1, 2, 3, 4, 5], 'col4': [1, 2, 3, 4, 5] }) # 计算相关性矩阵 corr_matrix = df.corr() # 使用 seaborn 绘制热度 sns.heatmap(corr_matrix, cmap='coolwarm', annot=True) ``` 上述代码首先导入了必要的库,然后创建了一个包含多个数值列的 DataFrame。通过调用 `DataFrame.corr()` 方法,可以计算出各列之间的相关性矩阵。最后使用 `seaborn.heatmap()` 函数绘制热度,其中 `cmap` 参数用于设置颜色映射,`annot=True` 表示在每个单元格中显示数值[^1]。 除了 `seaborn`,也可以使用 `matplotlib` 原生函数绘制热度,但通常推荐使用 `seaborn` 因为其更简洁的接口和更美观的默认样式。 对于更高级的需求,如交互式热度,可以结合 `plotly` 或 `heatmaply`(通过 R 的 `heatmaply` 包)实现。例如,`heatmaply` 支持聚类和交互式缩放功能[^2]。 ### 自定义热度 热度的自定义选项包括颜色映射、注释显示、聚类、边框等。例如,可以使用 `cmap` 参数指定不同的颜色渐变方案,如 `'viridis'`、`'plasma'`、`'inferno'` 等。此外,`vmin` 和 `vmax` 可用于限制颜色映射的范围,以突出特定的数据区间。 ### 应用场景 热度广泛应用于数据分析、基因组学、金融分析、像处理等多个领域。例如,在基因组学中,热度用于展示不同基因在不同样本中的表达水平;在金融分析中,热度可用于展示不同资产之间的相关性;在像处理中,热度可用于可视化模型的注意力区域。 ### 相关问题 热度可以其他数据可视化技术结合使用,例如聚类分析、主成分分析(PCA)等,以增强数据的可解释性。此外,还可以结合显著性检验(如 ANOVA)来标记热度中具有统计显著性的区域[^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wangbowj123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值