首页 > 解决方案 > 如何以索引为轴绘制列值

问题描述

我有一个数据框df:

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

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

我有兴趣说明 和 之间给出的ColumnA相关ColumnBdf['correlation']。这样做的最好方法是什么?

一种选择可能是绘制这种图:

在此处输入图像描述

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

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

标签: pythondataframematplotlibplotseaborn

解决方案


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

具有辅助 y 轴的单列热图


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


推荐阅读