使用matplotlib的Python中的相关图颜色不匹配

时间:2018-12-19 05:06:16

标签: python matplotlib machine-learning correlation

我正在使用matplotlib在python中绘制数据的相关性。高度相关的数据应显示为深红色,但在本例中为黄色。如何解决?

我的相关数据是:

Screen shot

我的代码是这样的:

def plot_corr(df, size=11):

"""\
Function plots a graphical correlation matrix for each pair of columns in the dataframe.

Input:
    df: pandas Dataframe
    size: vertical and horizontal size of the plot

Displays:
    matrix of correlation between columns. Blue-cyan-yellow-red-darkred => less to more correlated
                                           0 ------------------------> 1
                                           Expect a darkred line running from top left to bottom right
"""
corr = df.corr()    #data frame correlation function
fig, ax = plt.subplots(figsize=(size,size))
ax.matshow(corr)    # color code  the rectangles by correlation value
plt.xticks(range(len(corr.columns)), corr.columns)   # draw x tick marks
plt.yticks(range(len(corr.columns)), corr.columns)   # draw y tick marks

我的输出是这样的:

Screen Shot

1 个答案:

答案 0 :(得分:0)

Matplotlib将默认颜色图从“ jet”更改为“ viridis”,第一个将最大值映射为深红色,第二个映射为亮黄色。

更改不是免费的,新的颜色映射比旧的具有许多优势(如果您对原因感兴趣,请参阅此github issue

一种可能性是保持默认值不受干扰,并可能更改描述颜色范围的部分中的文档字符串...

    """\
...
Displays:
    matrix of correlation between columns. Blue-teal-green-yellow => less to more correlated
                                           0 ------------------------> 1
                                           Expect a bright yellow line running from top left to bottom right.
    """

另一种方法是明确提及您要使用的颜色图

def plot_corr(df, size=11):
    ...
    import matplotlib.cm as cm
    ...
    plt.matshow(corr, cmap=cm.jet)
    ...

最后一种可能性是在调用程序级别将 ALL 恢复为Matplotlib的默认设置

plt.style.use('classic')

或功能级别

    ...
    with plt.style.context('default'):
        plt.matshow(corr)
        ...