Seaborn diverging_palette有超过2种色调

时间:2018-06-04 14:23:41

标签: seaborn colormap

我试图使用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()

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以使用LinearSegmentedColormap从颜色列表中创建颜色映射,以便您可以实现diverging_pallette的效果,并且可以更好地控制颜色转换。

将此代码插入上面的示例中,可以得到我正在搜索的效果:

from matplotlib.colors import LinearSegmentedColormap
cmap = LinearSegmentedColormap.from_list(
    name='test', 
    colors=['red','white','green','white','red']
)

enter image description here