【问题标题】:How to plot a column value with its index as axis如何以索引为轴绘制列值
【发布时间】:2021-06-03 04:53:04
【问题描述】:

我有一个数据框 df:

ColumnA  ColumnB  correlation
dog1     cat1     3.6
dog2     cat2     2.9
dog3     cat3     -2.5

实际上,我在数据框中有 50 行。为了简单起见,我在这里只用 3 行来表示它。

我有兴趣说明ColumnAColumnB 之间的相关性,这在df['correlation'] 中给出。最好的方法是什么?

其中一种选择可能是绘制这样的图:

但是,我不确定如何使用 matplotlib 或任何其他 python 模块绘制相同的图。另外,如何在图上只保留一个轴。例如,仅保留左侧的 ColumnA 轴,并从右侧移除 ColumnB 轴。

欢迎以更好的方式表示相同的其他建议。

【问题讨论】:

    标签: python dataframe matplotlib plot seaborn


    【解决方案1】:

    使用sns.heatmap,我们可以绘制单列热图,然后调整 y 轴以放置额外的标签:

    fig, (cbar_ax, box_ax_0) = plt.subplots(
        nrows=1, 
        ncols=2, 
        gridspec_kw={'width_ratios': [1, 19]},
    )
    sns.heatmap(
        data=df["correlation"].to_numpy().reshape(-1,1), 
        annot=True,
        fmt='.2f',
        vmin=-5, 
        vmax=5, 
        square=True, 
        ax=box_ax_0,
        cbar_ax=cbar_ax,
    )
    # rotate the first set of ticks
    box_ax_0.set_yticklabels(df["ColumnA"], rotation="horizontal")
    
    # remove x-axis ticks
    box_ax_0.xaxis.set_ticks([])
    
    # Duplicate the y-axis
    box_ax_1 = box_ax_0.secondary_yaxis("right")
    # copy ticks from the first y-axis
    box_ax_1.set_yticks(box_ax_0.get_yticks())
    # add `ColumnB` labels 
    box_ax_1.set_yticklabels(df["ColumnB"])
    
    # remove spines from secondary axis
    box_ax_1.spines['right'].set_visible(False)
    
    # tweak layout to bring the colour bar closer
    plt.tight_layout()
    


    如果要反转颜色图,可以在sns.heatmap 函数调用中设置cmap="rocket_r"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-24
      • 2018-06-17
      • 1970-01-01
      • 2021-11-17
      • 2020-07-14
      相关资源
      最近更新 更多