当前位置:主页 > 软件编程 > Python代码 >

python seaborn heatmap可视化相关性矩阵实例

时间:2022-07-03 09:31:15 | 栏目:Python代码 | 点击:

方法

import pandas as pd
import numpy as np
import seaborn as sns
df = pd.DataFrame(np.random.randn(50).reshape(10,5))
corr = df.corr()
sns.heatmap(corr, cmap='Blues', annot=True)

将矩阵型简化为对角矩阵型:

mask = np.zeros_like(corr)
mask[np.tril_indices_from(mask)] = True
sns.heatmap(corr, cmap='Blues', annot=True, mask=mask.T)

补充知识:Python【相关矩阵】和【协方差矩阵】

相关系数矩阵

pandas.DataFrame(数据).corr()

import pandas as pd
df = pd.DataFrame({
  'a': [11, 22, 33, 44, 55, 66, 77, 88, 99],
  'b': [10, 24, 30, 48, 50, 72, 70, 96, 90],
  'c': [91, 79, 72, 58, 53, 47, 34, 16, 10],
  'd': [99, 10, 98, 10, 17, 10, 77, 89, 10]})
df_corr = df.corr()
# 可视化
import matplotlib.pyplot as mp, seaborn
seaborn.heatmap(df_corr, center=0, annot=True, cmap='YlGnBu')
mp.show()

协方差矩阵

numpy.cov(数据)

import numpy as np
matric = [
  [11, 22, 33, 44, 55, 66, 77, 88, 99],
  [10, 24, 30, 48, 50, 72, 70, 96, 90],
  [91, 79, 72, 58, 53, 47, 34, 16, 10],
  [55, 20, 98, 19, 17, 10, 77, 89, 14]]
covariance_matrix = np.cov(matric)
# 可视化
print(covariance_matrix)
import matplotlib.pyplot as mp, seaborn
seaborn.heatmap(covariance_matrix, center=0, annot=True, xticklabels=list('abcd'), yticklabels=list('ABCD'))
mp.show()

补充

协方差

相关系数

EXCEL也能做

CORREL函数

您可能感兴趣的文章:

相关文章