我有一个具有大量特征的数据集,因此分析相关矩阵变得非常困难。我想绘制一个相关矩阵,我们使用dataframe.corr()函数从pandas库中获得。pandas库是否提供了任何内置函数来绘制这个矩阵?
当前回答
试试这个函数,它也会显示相关矩阵的变量名:
def plot_corr(df,size=10):
"""Function plots a graphical correlation matrix for each pair of columns in the dataframe.
Input:
df: pandas DataFrame
size: vertical and horizontal size of the plot
"""
corr = df.corr()
fig, ax = plt.subplots(figsize=(size, size))
ax.matshow(corr)
plt.xticks(range(len(corr.columns)), corr.columns)
plt.yticks(range(len(corr.columns)), corr.columns)
其他回答
你可以使用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);
我更喜欢用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()
试试这个函数,它也会显示相关矩阵的变量名:
def plot_corr(df,size=10):
"""Function plots a graphical correlation matrix for each pair of columns in the dataframe.
Input:
df: pandas DataFrame
size: vertical and horizontal size of the plot
"""
corr = df.corr()
fig, ax = plt.subplots(figsize=(size, size))
ax.matshow(corr)
plt.xticks(range(len(corr.columns)), corr.columns)
plt.yticks(range(len(corr.columns)), corr.columns)
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()
你可以通过绘制海洋出生的热图或熊猫的散射矩阵来观察特征之间的关系。
散射矩阵:
pd.scatter_matrix(dataframe, alpha = 0.3, figsize = (14,8), diagonal = 'kde');
如果你想可视化每个特征的偏度,也可以使用海运配对图。
sns.pairplot(dataframe)
党Heatmap:
import seaborn as sns
f, ax = pl.subplots(figsize=(10, 8))
corr = dataframe.corr()
sns.heatmap(corr,
cmap=sns.diverging_palette(220, 10, as_cmap=True),
vmin=-1.0, vmax=1.0,
square=True, ax=ax)
输出将是特征的相关映射。参见下面的例子。
杂货店和洗涤剂之间的相关性很高。类似的:
高相关性产品:
杂货和洗涤剂。
相关性中等的产品:
牛奶和杂货 牛奶和洗涤剂。纸
低相关性产品:
牛奶和熟食 冷冻和新鲜。 冷冻熟食店。
从配对图中:你可以从配对图或散射矩阵中观察到相同的一组关系。但从这些可以判断数据是否正态分布。
注:上图为取自数据的同一张图,用于绘制热图。
推荐文章
- 数据类vs类型。NamedTuple主要用例
- 如何从macOS完全卸载蟒蛇
- 是否有可能键入提示一个lambda函数?
- 'dict'对象没有has_key属性
- 使用Pandas groupby连接来自几行的字符串
- Pandas:给定列的数据帧行之和
- 如何避免在为Python项目构建Docker映像时重新安装包?
- 如何激活蟒蛇环境
- 省略[…]意思是在一个列表里?
- 为什么我得到“'str'对象没有属性'读取'”当尝试使用' json。载入字符串?
- 不区分大小写的列表排序,没有降低结果?
- 排序后的语法(key=lambda:…)
- 在烧瓶中返回HTTP状态代码201
- 使用python创建一个简单的XML文件
- APT命令行界面式的yes/no输入?