[英]How to keep the ones in the Diagonal of sns.heatmap?
我想 plot 与 sns.heatmap 的相关矩阵并有一些问题。 这是我的代码:
plt.figure(figsize=(8,8)) mask =np.zeros_like(data.corr()) mask[np.triu_indices_from(mask)] = True sns.heatmap(data.corr(), mask=mask, linewidth=1, annot=True, fmt=".2f",cmap='coolwarm',vmin=-1, vmax=1) plt.show()
这就是我得到的:[相关矩阵][1] [1]: https://i.stack.imgur.com/DX2oN.png \
现在我有一些问题:
1)我怎样才能把那些放在对角线上?
2)如何改变x轴的position?
3) 我希望颜色条从 1 变为 -1,但代码不工作
我希望有人能帮帮忙。
谢谢
我认为您必须检查data.corr()
,因为您的代码正确并且可以诊断(请参阅下文)。 一个问题是:您使用np.triu
但显示的图片显示np.tirl
。
这是我测试过的代码-对角线在这里:
N = 5
A = np.arange(N*N).reshape(N,N)
B = np.tril(A)
mask =np.zeros_like(A)
mask[np.triu_indices_from(mask)] = True
print('A'); print(A); print()
print('tril(A)'); print(B); print()
print('mask'); print(mask); print()
给
A
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
tril(A)
[[ 0 0 0 0 0]
[ 5 6 0 0 0]
[10 11 12 0 0]
[15 16 17 18 0]
[20 21 22 23 24]]
mask
[[1 1 1 1 1]
[0 1 1 1 1]
[0 0 1 1 1]
[0 0 0 1 1]
[0 0 0 0 1]]
编辑:补充
您可以重新调整面膜,例如
C = A *mask
D = np.where(C > 1, 1,C)
print('D'); print(D)
给
D
[[0 1 1 1 1]
[0 1 1 1 1]
[0 0 1 1 1]
[0 0 0 1 1]
[0 0 0 0 1]]
D的对角线的第一个元素现在为零,因为A的对角线的第一个元素也为零。
编辑:补充2
F = np.tril(A,-1)
E = np.eye(N)
G = E + F
print('F'); print(F); print()
print('E'); print(E); print()
print('G'); print(G); print()
给
F
[[ 0 0 0 0 0]
[ 5 0 0 0 0]
[10 11 0 0 0]
[15 16 17 0 0]
[20 21 22 23 0]]
E
[[1. 0. 0. 0. 0.]
[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]]
G
[[ 1. 0. 0. 0. 0.]
[ 5. 1. 0. 0. 0.]
[10. 11. 1. 0. 0.]
[15. 16. 17. 1. 0.]
[20. 21. 22. 23. 1.]]
mask[np.triu_indices_from(mask)]
将定义三角形(包括对角线)
mask[np.eye(mask.shape[0], dtype=bool)]
将定义对角线。
如果将它们放在一起,则可以独立控制它们。 (请注意,您需要在对角线之前设置三角形)。
def plot_correlation_matrix(df, remove_diagonal=True, remove_triangle=False, **kwargs):
corr = df.corr()
# Apply mask
mask = np.zeros_like(corr, dtype=np.bool)
mask[np.triu_indices_from(mask)] = remove_triangle
mask[np.eye(mask.shape[0], dtype=bool)] = remove_diagonal
# Plot
# plt.figure(figsize=(8,8))
sns.heatmap(corr, mask=mask, **kwargs)
plt.show()
所以此命令将生成矩阵,移除上三角,但保留对角线:
plot_correlation_matrix(df[colunas_notas], remove_diagonal=False, remove_triangle=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.