为什么我的相关矩阵显示的是全白色图片?

2024-09-25 10:26:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用以下代码绘制了相关矩阵:

sns.set_theme(style="white")

# Compute the correlation matrix
corr = final_df.T.corr()

# Generate a mask for the upper triangle
mask = np.triu(np.ones_like(corr, dtype=bool))

# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(24, 12))

# Generate a custom diverging colormap
cmap = sns.diverging_palette(230, 20, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,
            square=True, linewidths=.5, cbar_kws={"shrink": .5})

结果是:

enter image description here

我不明白为什么会这样。我尝试了另一种方法:

corr = df.corr()
fig, ax = plt.subplots(figsize=(24, 12))
ax.matshow(corr, vmin=0,vmax=1)
plt.xticks(range(len(corr.columns)), corr.columns, rotation='vertical', fontsize=8);
plt.yticks(range(len(corr.columns)), corr.columns, fontsize=8);

但结果仍然是:

enter image description here

我的数据似乎不坏。下面是相关矩阵的样子:

enter image description here

有人能解释一下为什么会发生这种情况,以及如何解决它吗

事先非常感谢

编辑

回应@mwaskom的评论。我删除了linewidth = .5参数,问题似乎部分解决了。我之所以这样说,部分原因是因为一些点开始出现在情节中,但不可能真实地想象任何东西

这是删除linewidth参数后得到的结果:

enter image description here

我试过用一个更大的无花果尺寸(36,24)在它(24,12)之前,但它仍然是一样的。这是一个截图(截图无法捕获整个数字)

enter image description here

有没有办法让这个图有助于可视化相关性

更新

使用Arty的答案得出的结果仍然非常相似。以下是截图:

enter image description here

我在评论中也尝试了约翰的建议。这一次更接近产生有意义的结果,但仍然:

enter image description here

您有什么建议吗

多谢各位


Tags: columnsthetruedfnppltmaskax
1条回答
网友
1楼 · 发布于 2024-09-25 10:26:34

我想你有办法得到很多数值来查看任何有意义的热图,因为我尝试用非常小的数组来重现你的图片,并成功了。尝试一次显示较少的值。同时设置vmin = -1, vmax = 1。我的代码是:

Try it online!

import numpy as np, matplotlib.pyplot as plt, seaborn as sns

sns.set_theme(style="white")

# Compute the correlation matrix
corr = np.array([[1, 0, 0], [-0.2, 1, 0], [0.3, 0.7, 1]], dtype = np.float64)

# Generate a mask for the upper triangle
mask = np.triu(np.ones_like(corr, dtype=bool))

# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(24, 12))

# Generate a custom diverging colormap
cmap = sns.diverging_palette(230, 20, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, mask=mask, cmap=cmap, vmin=-1, vmax=1, center=0,
            square=True, cbar_kws={"shrink": .5})
            
plt.show()

输出:

enter image description here

相关问题 更多 >