我有一个具有大量特征的数据集,因此分析相关矩阵变得非常困难。我想绘制一个相关矩阵,我们使用dataframe.corr()函数从pandas库中获得。pandas库是否提供了任何内置函数来绘制这个矩阵?


当前回答

如果你的dataframe是df,你可以简单地使用:

import matplotlib.pyplot as plt
import seaborn as sns

plt.figure(figsize=(15, 10))
sns.heatmap(df.corr(), annot=True)

其他回答

当处理大量特征之间的相关性时,我发现将相关特征聚类在一起很有用。这可以用seaborn clustermap图来完成。

import seaborn as sns
import matplotlib.pyplot as plt

g = sns.clustermap(df.corr(), 
                   method = 'complete', 
                   cmap   = 'RdBu', 
                   annot  = True, 
                   annot_kws = {'size': 8})
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=60);

clustermap函数使用层次聚类将相关特征排列在一起并生成树状树状图。

在这个图中有两个值得注意的集群:

Y_des和dew.point_des Irradiance, y_seasonal和dew.point_seasonal


FWIW的气象数据,以产生这一数字可以访问与这木星笔记本。

Statmodels图形也提供了一个很好的相关矩阵视图

import statsmodels.api as sm
import matplotlib.pyplot as plt

corr = dataframe.corr()
sm.graphics.plot_corr(corr, xnames=list(corr.columns))
plt.show()

形成相关矩阵,在我的情况下,zdf是我需要执行相关矩阵的数据框架。

corrMatrix =zdf.corr()
corrMatrix.to_csv('sm_zscaled_correlation_matrix.csv');
html = corrMatrix.style.background_gradient(cmap='RdBu').set_precision(2).render()

# Writing the output to a html file.
with open('test.html', 'w') as f:
   print('<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-widthinitial-scale=1.0"><title>Document</title></head><style>table{word-break: break-all;}</style><body>' + html+'</body></html>', file=f)

然后我们可以截屏。或者将HTML转换为图像文件。

如果你的主要目标是可视化相关矩阵,而不是创建一个图形本身,方便的pandas样式选项是一个可行的内置解决方案:

import pandas as pd
import numpy as np

rs = np.random.RandomState(0)
df = pd.DataFrame(rs.rand(10, 10))
corr = df.corr()
corr.style.background_gradient(cmap='coolwarm')
# 'RdBu_r', 'BrBG_r', & PuOr_r are other good diverging colormaps

请注意,这需要在支持呈现HTML的后端中,例如JupyterLab Notebook。


样式

您可以轻松地限制数字精度:

corr.style.background_gradient(cmap='coolwarm').set_precision(2)

如果你更喜欢没有注释的矩阵,也可以把数字都去掉:

corr.style.background_gradient(cmap='coolwarm').set_properties(**{'font-size': '0pt'})

样式文档还包括更高级样式的说明,例如如何更改鼠标指针悬停的单元格的显示。


时间比较

在我的测试中,style.background_gradient()比plt.matshow()快4倍,比sn .heatmap()快120倍,矩阵为10x10。不幸的是,它的伸缩性不如plt.matshow():对于100x100的矩阵,两者需要相同的时间,而对于1000x1000的矩阵,plt.matshow()要快10倍。


储蓄

有几种可能的方法来保存风格化的数据框架:

通过追加render()方法返回HTML,然后将输出写入文件。 通过附加to_excel()方法保存为带有条件格式的.xslx文件。 结合imgkit保存位图 截屏(就像我在这里所做的那样)。


将整个矩阵的颜色归一化(pandas >= 0.24)

通过设置axis=None,现在可以基于整个矩阵计算颜色,而不是每列或每行:

corr.style.background_gradient(cmap='coolwarm', axis=None)


单角热图

由于很多人正在阅读这个答案,我想我应该添加一个技巧,如何只显示相关矩阵的一个角落。我发现这个更容易阅读,因为它删除了多余的信息。

# Fill diagonal and upper half with NaNs
mask = np.zeros_like(corr, dtype=bool)
mask[np.triu_indices_from(mask)] = True
corr[mask] = np.nan
(corr
 .style
 .background_gradient(cmap='coolwarm', axis=None, vmin=-1, vmax=1)
 .highlight_null(null_color='#f1f1f1')  # Color NaNs grey
 .set_precision(2))

你可以使用matplotlib中的pyplot.matshow():

import matplotlib.pyplot as plt

plt.matshow(dataframe.corr())
plt.show()

编辑:

在评论中有一个关于如何更改轴勾标签的请求。这是一个豪华版,它画在一个更大的图形尺寸上,有轴标签来匹配数据框架,还有一个颜色条图例来解释颜色尺度。

我包括如何调整标签的大小和旋转,我正在使用一个图形比例,使颜色条和主要图形出来的高度相同。


编辑2: 由于df.corr()方法忽略非数值列,在定义x和y标签时应该使用.select_dtypes(['number']),以避免不必要的标签移位(包括在下面的代码中)。

f = plt.figure(figsize=(19, 15))
plt.matshow(df.corr(), fignum=f.number)
plt.xticks(range(df.select_dtypes(['number']).shape[1]), df.select_dtypes(['number']).columns, fontsize=14, rotation=45)
plt.yticks(range(df.select_dtypes(['number']).shape[1]), df.select_dtypes(['number']).columns, fontsize=14)
cb = plt.colorbar()
cb.ax.tick_params(labelsize=14)
plt.title('Correlation Matrix', fontsize=16);