我有一个具有大量特征的数据集,因此分析相关矩阵变得非常困难。我想绘制一个相关矩阵,我们使用dataframe.corr()函数从pandas库中获得。pandas库是否提供了任何内置函数来绘制这个矩阵?
当前回答
形成相关矩阵,在我的情况下,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转换为图像文件。
其他回答
请检查下面可读的代码
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=(36, 26))
heatmap = sns.heatmap(df.corr(), vmin=-1, vmax=1, annot=True)
heatmap.set_title('Correlation Heatmap', fontdict={'fontsize':12}, pad=12)```
[1]: https://i.stack.imgur.com/I5SeR.png
Seaborn的热图版本:
import seaborn as sns
corr = dataframe.corr()
sns.heatmap(corr,
xticklabels=corr.columns.values,
yticklabels=corr.columns.values)
corrmatrix = df.corr()
corrmatrix *= np.tri(*corrmatrix.values.shape, k=-1).T
corrmatrix = corrmatrix.stack().sort_values(ascending = False).reset_index()
corrmatrix.columns = ['Признак 1', 'Признак 2', 'Корреляция']
corrmatrix[(corrmatrix['Корреляция'] >= 0.7) + (corrmatrix['Корреляция'] <= -0.7)]
drop_columns = corrmatrix[(corrmatrix['Корреляция'] >= 0.82) + (corrmatrix['Корреляция'] <= -0.7)]['Признак 2']
df.drop(drop_columns, axis=1, inplace=True)
corrmatrix[(corrmatrix['Корреляция'] >= 0.7) + (corrmatrix['Корреляция'] <= -0.7)]
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()
我更喜欢用Plotly,因为它的图表更具交互性,也更容易理解。可以使用下面的代码片段。
import plotly.express as px
def plotly_corr_plot(df,w,h):
fig = px.imshow(df.corr())
fig.update_layout(
autosize=False,
width=w,
height=h,)
fig.show()