python - 如何以索引为轴绘制列值
问题描述
我有一个数据框df:
ColumnA ColumnB correlation
dog1 cat1 3.6
dog2 cat2 2.9
dog3 cat3 -2.5
实际上,我在数据框中有 50 行。为了简单起见,我在这里只用 3 行来表示它。
我有兴趣说明 和 之间给出的ColumnA
相关ColumnB
性df['correlation']
。这样做的最好方法是什么?
一种选择可能是绘制这种图:
但是,我不确定如何使用 matplotlib 或任何其他 python 模块来绘制相同的图。另外,如何在图上只保留一个轴。例如,仅保留左侧的 ColumnA 轴,并从右侧删除 ColumnB 轴。
欢迎其他以更好的方式表示相同的建议。
解决方案
使用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()
如果要反转颜色图,可以cmap="rocket_r"
在sns.heatmap
函数调用中设置。
推荐阅读
- html - 将 URL 参数传递给表单输入,而不在表单发布后重置
- sql - 使用前几行中的值更新表,然后在下一次计算中使用输出值
- javascript - 我如何像在 concat() 中那样将多个值传递给函数?
- java - 增加Tomcat关闭超时
- r - GAMs 空间分析 (mgcv) - 添加地图进行可视化
- python - 找不到 Python (VSCODE)
- php - 原则:当 mysql 服务器关闭时,不可能捕获异常
- python - 是否有任何在 Python 中实现高斯和雅可比算法的预定义函数?
- mapping - 从 userinfo 检索公共地图数据
- excel - 一旦加载 XML 文档,VBA 代码就会失败