代码之家  ›  专栏  ›  技术社区  ›  user8834780

部分相关可视化

  •  1
  • user8834780  · 技术社区  · 6 年前

    从下面的答案 https://stats.stackexchange.com/questions/288273/partial-correlation-in-panda-dataframe-python

    dict = {'x1': [1, 2, 3, 4, 5], 'x2': [2, 2, 3, 4, 2], 'x3': [10, 9, 5, 4, 9], 'y' : [5.077, 32.330, 65.140, 47.270, 80.570]} 
    df = pd.DataFrame(dict, columns=['x1', 'x2', 'x3', 'y'])
    partial_corr_array = df.as_matrix()
    np.round(partial_corr(partial_corr_array), decimals=2)
    

    array([[ 1.  ,  0.52,  0.15,  0.91],
           [ 0.52,  1.  ,  0.25, -0.25],
           [ 0.15,  0.25,  1.  , -0.06],
           [ 0.91, -0.25, -0.06,  1.  ]])
    

    与相同 df.corr().style.background_gradient() ? 热图和注解。

    请注意,这是一个偏相关,即我们控制其他变量的影响。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Sheldore    6 年前

    你的意思是这样的:

    import matplotlib.pyplot as plt
    partial_corr_array = np.array([[ 1., 0.52, 0.15, 0.91], [ 0.52, 1., 0.25, -0.25], [ 0.15,  0.25,  1.  , -0.06], [ 0.91, -0.25, -0.06,  1.  ]])
    plt.matshow(partial_corr_array)
    plt.colorbar()
    

    输出

    enter image description here

    图2 基于 this

    import seaborn as sns
    f, ax = plt.subplots(figsize=(6, 5))
    partial_corr_array = np.array([[ 1., 0.52, 0.15, 0.91], [ 0.52, 1., 0.25, -0.25], [ 0.15,  0.25,  1.  , -0.06], [ 0.91, -0.25, -0.06,  1.  ]])
    mask = np.zeros_like(partial_corr_array, dtype=np.bool)
    mask[np.triu_indices_from(mask)] = True
    cmap = sns.diverging_palette(30, 10, as_cmap=True)
    sns.heatmap(partial_corr_array, mask=mask, cmap=cmap, vmax=1, center=0,
                square=True, linewidths=1, cbar_kws={"shrink": 0.9}, annot=True)
    

    输出

    enter image description here

        2
  •  0
  •   CT Zhu    6 年前

    seaborn.heatmap 提供的正是这个,使用 fmt 控制面值字符串格式,并使用 annot 要控制是否显示面值(默认为False):

    DataFrame.corr

    In [28]: import seaborn as sns
    In [39]: sns.heatmap(df.corr(), fmt='0.2f', annot=True)
    Out[39]: <matplotlib.axes._subplots.AxesSubplot at 0xd961048>
    

    enter image description here