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

Pandas DataFrame定制热力图绘制求助:自定义配色与样式

Solution

First, reconstruct your DataFrame correctly, then use Seaborn to generate the custom heatmap that meets all your requirements. Here's a complete working example:

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

# 1. Reconstruct your DataFrame
data = {
    'cell1': [1, np.nan, 3, 2, np.nan, 3],
    'cell2': [np.nan, 3, np.nan, 3, 2, 1],
    'cell3': [np.nan, np.nan, 2, np.nan, 3, np.nan]
}
row_indices = ['', 'Cell1', 'Cell2', 'Cell3', 'Cell4', 'Cell5']
df = pd.DataFrame(data, index=row_indices)

# 2. Define custom color mapping and colormap
# Adjust hex codes to tweak brightness (e.g., #ffaaaa for lighter red)
color_mapping = {
    np.nan: '#ffffff',   # NaN → white
    1: '#ff4444',        # 1 → dark red
    2: '#ffff44',        # 2 → bright yellow
    3: '#4444ff'         # 3 → dark blue
}

# Replace NaN with placeholder (0) for consistent color mapping
df_heatmap = df.fillna(0)
# Create discrete colormap
colors = [color_mapping[0], color_mapping[1], color_mapping[2], color_mapping[3]]
cmap = plt.cm.ListedColormap(colors)
# Set boundaries to ensure each value maps to the correct color
bounds = [-0.5, 0.5, 1.5, 2.5, 3.5]
norm = plt.cm.colors.BoundaryNorm(bounds, cmap.N)

# 3. Generate the heatmap
plt.figure(figsize=(7, 5))
ax = sns.heatmap(
    df_heatmap,
    annot=False,          # Hide cell values
    cmap=cmap,
    norm=norm,
    linewidths=1,         # Add black cell borders
    linecolor='black',
    cbar=False            # Optional: remove to show color legend
)

# 4. Adjust column labels (move to bottom, rotate)
ax.set_xticklabels(ax.get_xticklabels(), rotation=45, ha='right')
ax.tick_params(axis='x', bottom=True, top=False, labelbottom=True, labeltop=False)

# Keep row labels horizontal
ax.set_yticklabels(ax.get_yticklabels(), rotation=0)

plt.tight_layout()
plt.show()

Key Details:

  • Custom Brightness: Modify the hex color codes to adjust brightness (e.g., #ffaaaa for a lighter red instead of #ff4444).
  • Black Borders: linewidths=1 and linecolor='black' add solid black borders around every cell.
  • Hidden Values: annot=False ensures only color is visible in cells.
  • Column Placement: Tick parameter adjustments move column labels to the bottom and rotate them for readability.

If you need an HTML-based heatmap (for web/reports), use pandas Styler:

def style_cell(val):
    if pd.isna(val):
        return 'background-color: #ffffff; border: 1px solid black;'
    elif val == 1:
        return 'background-color: #ff4444; border: 1px solid black;'
    elif val == 2:
        return 'background-color: #ffff44; border: 1px solid black;'
    elif val == 3:
        return 'background-color: #4444ff; border: 1px solid black;'
    return ''

# Apply styling and hide cell values
styled_table = df.style.applymap(style_cell).format(lambda x: '')

# Adjust column header styling
styled_table.set_table_styles([
    {
        'selector': 'th.col_heading',
        'props': [
            ('text-align', 'center'),
            ('transform', 'rotate(45deg)'),
            ('vertical-align', 'top'),
            ('padding', '10px 5px')
        ]
    }
])

# Save to HTML or display in notebook
styled_table.to_html('custom_heatmap.html')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 20:30:55