使用 pandas 绘制相关矩阵 [英] Plot correlation matrix using pandas
问题描述
我有一个包含大量特征的数据集,因此分析相关矩阵变得非常困难.我想绘制一个相关矩阵,我们使用熊猫库中的dataframe.corr()
函数获得该矩阵. pandas库是否提供任何内置函数来绘制此矩阵?
I have a data set with huge number of features, so analysing the correlation matrix has become very difficult. I want to plot a correlation matrix which we get using dataframe.corr()
function from pandas library. Is there any built-in function provided by the pandas library to plot this matrix?
推荐答案
您可以使用 pyplot.matshow()
来自matplotlib
:
import matplotlib.pyplot as plt
plt.matshow(dataframe.corr())
plt.show()
在注释中,要求更改轴刻度标签.这是一个豪华的版本,它使用较大的图形尺寸绘制,具有与数据框匹配的轴标签,以及用于解释色阶的色条图例.
In the comments was a request for how to change the axis tick labels. Here's a deluxe version that is drawn on a bigger figure size, has axis labels to match the dataframe, and a colorbar legend to interpret the color scale.
我将介绍如何调整标签的大小和旋转角度,并使用数字比例使颜色条和主图形的高度相同.
I'm including how to adjust the size and rotation of the labels, and I'm using a figure ratio that makes the colorbar and the main figure come out the same height.
f = plt.figure(figsize=(19, 15))
plt.matshow(df.corr(), fignum=f.number)
plt.xticks(range(df.shape[1]), df.columns, fontsize=14, rotation=45)
plt.yticks(range(df.shape[1]), df.columns, fontsize=14)
cb = plt.colorbar()
cb.ax.tick_params(labelsize=14)
plt.title('Correlation Matrix', fontsize=16);
这篇关于使用 pandas 绘制相关矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!