我试图使用Seaborn绘制相关矩阵,但我想突出显示红色的正极值和负极值以及绿色的中间值。在我能找到的所有例子中,相关矩阵用diverging_palette绘制,但这只允许你为光谱的两端选择两种颜色,并为中间选择浅色(白色)或深色(黑色)值。在StackOverflow和其他网站上搜索后,我无法找到解决方案,所以我发布了我找到的解决方案。
以下是Seaborn的例子:
https://seaborn.pydata.org/examples/many_pairwise_correlations.html https://seaborn.pydata.org/generated/seaborn.heatmap.html
以下是生成下图以说明问题的代码。我正在寻找的是绿色为0值,红色为正值和负值。
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
np.random.seed(5)
df = pd.DataFrame(np.random.randn(5,5))
# Generate a custom diverging colormap
cmap = sns.diverging_palette(133, 10, as_cmap=True)
with sns.axes_style("white"):
ax = sns.heatmap(df, annot=True, fmt='.2f', cmap=cmap, vmin=-0.99, vmax=.99, center=0.00,
square=True, linewidths=.5, annot_kws={"size": 8}, cbar_kws={"shrink": .5})
plt.show()