绘制关系矩阵的时候使用的是seaborn中的热图
sns.headtmap(df.corr(),cmap='cubehelix_r'
绘制关系矩阵df.corr().style.background_gradient(cmap='coolwarm').set_percision(2)
绘制关系表格- 通过关系矩阵和关系表格找到和我们的标签(label)相关性最强的列
- 分类特征和标签,分别对应x和y
关系矩阵实例:plt.figure(figsize=(8, 12))
heatmap = sns.heatmap(df.corr()[['units_sold']].sort_values(by='units_sold', ascending=False), vmin=-1, vmax=1, annot=True, cmap='BrBG')
heatmap.set_title(f'Features Correlating with units_sold', fontdict={'fontsize':18}, pad=16)
plt.figure(figsize=(12,8))
sns.heatmap(df.corr(),cmap='RdPu',annot=True)
当特征的数量比较多的时候,用下面这段代码
f, ax = plt.subplots(figsize=(30, 25))
mat = data.corr('pearson')
mask = np.triu(np.ones_like(mat, dtype=bool))
cmap = sns.diverging_palette(230, 20, as_cmap=True)
sns.heatmap(mat, mask=mask, cmap=cmap, vmax=1, center=0, annot = True,
square=True, linewidths=.5, cbar_kws={"shrink": .5})
- np.triu是numpy里面的一个函数,可以将矩阵的对角线上半部或者下半部的元素全部置为0,这样更加方便阅读关系矩阵图