You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

转置DataFrame后绘制Seaborn热力图出现空白图及索引问题求助

解决转置后热力图空白的索引问题

问题根源

直接对原始DataFrame调用transpose()后,数据结构完全错位:原列名(包括Indicators)变成了转置后DataFrame的索引,原行索引则成为转置后的列名。此时执行set_index('Indicators')会因找不到对应列导致数据处理失效,最终生成空白热力图。

正确处理逻辑

  1. 先将原始DataFrame的Indicators列设为行索引,保留所有Criteria列作为数据列
  2. 对处理后的DataFrame转置,此时转置结果会自动将Criteria作为Y轴(行)、Indicators作为X轴(列),完全匹配需求
  3. 基于转置后的正确结构绘制热力图

修正后的完整代码

import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap

# 读取数据,处理开头的无列名索引列
df = pd.read_csv('Res_Gov.csv', index_col=0)

# 先设置Indicators为索引,再转置得到目标结构
df_transposed = df.set_index('Indicators').transpose()

# 设置横向适配的画布尺寸
f, ax = plt.subplots(figsize=(16, 8))

# 自定义颜色映射
colors = ["#f4a261","#2a9d8f"] 
cmap = LinearSegmentedColormap.from_list('Custom', colors, len(colors))

# 绘制热力图
sns.heatmap(df_transposed, cmap=cmap, square=True, linewidths=.5, 
            cbar_kws={"shrink": .5}, ax=ax)

# 设置颜色条标签
colorbar = ax.collections[0].colorbar
colorbar.set_ticks([0.25, 0.75])
colorbar.set_ticklabels(['Not Applicable', 'Applicable'])

# 优化轴标签显示
ax.set_xlabel('Indicators')
ax.set_ylabel('Criteria')
plt.tight_layout()
plt.show()

关键细节说明

  • 读取数据时用index_col=0处理原数据开头的无列名索引列,避免生成多余的Unnamed: 0列干扰后续操作
  • 先set_index再转置,确保转置后的数据结构完全符合需求:Y轴展示各类Criteria,X轴展示所有Indicators
  • 调整画布为横向比例(如16:8),避免Indicators标签因数量过多出现重叠

内容的提问来源于stack exchange,提问作者JamesArthur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 18:05:06