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

在Jupyter Notebook中如何将数据透视表生成为带标签配色的图片?

在Jupyter Notebook中生成带标签配色的透视表样式图

要实现把普通数据透视表转换成你需要的带配色和标签的样式图,我们可以用pandas+matplotlib的组合来完成,以下是具体步骤:


1. 确保透视表为DataFrame格式

首先确认你的透视表已经是pandas.DataFrame类型,如果还没生成,用pivot_table()创建:

import pandas as pd

# 示例:生成透视表
raw_data = {
    "Region": ["North", "North", "South", "South", "East", "East"],
    "Product": ["A", "B", "A", "B", "A", "B"],
    "Sales": [120, 80, 95, 110, 130, 75]
}
df = pd.DataFrame(raw_data)
pivot_df = df.pivot_table(index="Region", columns="Product", values="Sales", aggfunc="sum")

2. 添加单元格配色

用pandas.Styler快速实现基于数值的渐变配色,在Jupyter中直接渲染带样式的表格:

import seaborn as sns

# 定义渐变配色方案(可根据需求替换成其他配色)
color_map = sns.diverging_palette(240, 10, as_cmap=True)

# 配置表格样式
styled_pivot = pivot_df.style.background_gradient(
    cmap=color_map,
    vmin=pivot_df.min().min(),
    vmax=pivot_df.max().max()
).set_table_styles([
    {"selector": "th", "props": [("background", "#f5f5f5"), ("font-weight", "bold"), ("text-align", "center")]},
    {"selector": "td", "props": [("text-align", "center")]}
]).set_caption("区域-产品销售业绩")

# 在Jupyter中显示带样式的表格
styled_pivot

3. 添加自定义标签/标注

如果需要像示例图那样添加箭头、高亮注释等元素,用matplotlib绘制表格并叠加标注:

import matplotlib.pyplot as plt
import numpy as np

# 创建绘图对象
fig, ax = plt.subplots(figsize=(7, 3.5))
ax.axis("off")  # 隐藏坐标轴

# 绘制透视表
table = ax.table(
    cellText=pivot_df.values,
    rowLabels=pivot_df.index,
    colLabels=pivot_df.columns,
    cellLoc="center",
    loc="center",
    colWidths=[0.3]*len(pivot_df.columns)
)

# 给单元格设置配色
min_val = pivot_df.min().min()
max_val = pivot_df.max().max()
for i in range(len(pivot_df.index)):
    for j in range(len(pivot_df.columns)):
        val = pivot_df.iloc[i, j]
        # 按数值映射颜色(渐变逻辑)
        norm_val = (val - min_val) / (max_val - min_val)
        cell_color = plt.cm.RdYlBu(norm_val)
        table[(i+1, j)].set_facecolor(cell_color)

# 添加自定义标注(示例:给最高销售额添加箭头注释)
max_pos = np.where(pivot_df.values == max_val)
ax.annotate(
    "最高业绩",
    xy=(max_pos[1]+0.5, max_pos[0]+1.2),
    xytext=(max_pos[1]+1, max_pos[0]+1.5),
    arrowprops=dict(facecolor="black", shrink=0.05, width=1)
)

# 设置标题
plt.title("区域-产品销售业绩", y=1.08, fontweight="bold")
plt.show()

4. 导出为图片文件

如果要将最终样式保存为图片,在matplotlib中调用savefig()即可:

# 保存为高清图片
plt.savefig("styled_pivot.png", bbox_inches="tight", dpi=300)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 21:50:38