0%

python数据分析与机器学习实战-18.热力图绘制

1
2
3
4
5
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
1
2
3
4
5
6
7
8
9
10
11
12
data = np.random.rand(3,3)
print(data)
heatmap = sns.heatmap(data)
[[0.79738421 0.16230573 0.06197724]
[0.79989397 0.73146068 0.17731879]
[0.26202278 0.78645707 0.26536331]]





<matplotlib.axes._subplots.AxesSubplot at 0x10d042a90>

png

1
2
#设置数据最小值到最大值界限
ax = sns.heatmap(data,vmin=0.1,vmax=0.5)

png

1
2
3
4
5
6
7
#当数据有正负时,可以指定以0为中心
data = np.random.randn(3,3)
print(data)
ax = sns.heatmap(data,center=0)
[[ 0.65257565 -0.38550847 0.55620784]
[ 0.28429021 -1.68905002 -0.29115511]
[-1.09649997 -0.81622564 0.47706824]]

png

1
2
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
1
2
3
4
5
#数据转换
flights = flights.pivot("month","year","passengers")
#热力图
sns.heatmap(flights)
<matplotlib.axes._subplots.AxesSubplot at 0x1a1a0a5ac8>

png

1
2
#将数据显示在heatmap中,annot=True,将fmt的值设置为'd',否则数据会出现乱码。
ax = sns.heatmap(flights,annot=True,fmt='d')

png

1
2
#heatmap格与格之间增加间隙
ax = sns.heatmap(flights,linewidth=0.5)

png

1
2
#设置自定义颜色
ax = sns.heatmap(flights,linewidth=0.5,cmap="YlGnBu")

png

# seaborn # heatmap