首页 > 解决方案 > 确定相关矩阵中的颜色代码

问题描述

我看到了如下代码。这是在具有 python 版本 3.7.3 的 Jupyter 上运行的。我在之前的教程中看到,列与自身的相关性为 1,因此在矩阵的那个单元格中看到了颜色 RED,但现在我看到自己尝试了一下,发现它是黄色的。这是因为颜色代码发生了变化还是由于 python 版本变化?如代码部分 "ax.matshow(corr)" 所示,这里似乎发生了一些变化。有没有办法定义我自己的颜色代码与强相关(0---->1)不相关

def plot_corr(df,size):
    '''
    Function plots graphical corelation matrix for each pair of column in dataframe
    Input: 
          df: pandas dataframe
          size: vertical and horizontal size of the plot
    Displays: 
            matrix of corelation between columns. Blue-cyan-yellow-red-darkred => less to more corelated
                                                  0-------------------->1
                                                  Expect a dark red line running from top left to bottom right
    '''

    corr=df.corr()  #data frame corelation funnction
    fig,ax= plt.subplots(figsize=(size,size))
    ax.matshow(corr)  #color code the matrix rectangles by corelation value
    plt.xticks(range(len(corr.columns)),corr.columns) #draw xticks mark

相关矩阵

标签: pythondataframematplotlibcorrelation

解决方案


这可以使用Matplotlib Colormaps来完成,它可以使用matshow参数添加到函数中cmap=plt.get_cmap(name)

例如,如果您想使用红色颜色图,例如Reds,运行

ax.matshow(corr, cmap=plt.get_cmap('Reds'))

推荐阅读