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

求创建同一注释行含双注释的Heatmap的实现方案(R/Python均可)

Got it! 我来给你分享两种靠谱的实现思路,分别用R和Python,都能搞定你想要的「同一注释行包含双注释」的热力图效果,和你用PPT做的示例风格对齐~

R 实现方案(基于ggplot2)

核心思路:先把要显示的双注释内容提前处理好(可以组合成带样式的文本),用ggplot2绘制基础热力图,再通过支持markdown的文本图层把双注释添加到对应单元格。

步骤1:准备带双注释的数据集

先构造包含得分和评级的示例数据,然后把两个注释内容组合成支持样式的文本:

library(ggplot2)
library(ggtext) # 用来解析markdown格式的文本,实现样式区分

set.seed(123) # 固定随机种子,结果可复现
heatmap_data <- expand.grid(
  Category = c("A", "B", "C", "D"),
  Group = c("G1", "G2", "G3", "G4")
)
heatmap_data$Score <- sample(60:100, 16, replace = TRUE)
# 生成评级注释
heatmap_data$Rating <- ifelse(heatmap_data$Score >= 90, "优秀", 
                             ifelse(heatmap_data$Score >= 80, "良好", "合格"))
# 组合双注释:把得分加粗,用竖线和评级分隔
heatmap_data$Double_Text <- paste0("*", heatmap_data$Score, "*", " | ", heatmap_data$Rating)

步骤2:绘制热力图并添加双注释

ggplot(heatmap_data, aes(x = Group, y = Category, fill = Score)) +
  geom_tile(color = "white", size = 1) + # 绘制热力图瓷砖,白色边框区分单元格
  scale_fill_gradient(low = "#f0f9e8", high = "#006d2c") + # 自定义渐变配色
  # 添加双注释,用geom_richtext解析markdown样式,去掉文本框背景
  geom_richtext(aes(label = Double_Text), 
                fill = NA, label.color = NA, 
                size = 4, ha = "center") +
  labs(title = "带双注释的热力图", x = "分组", y = "类别") +
  theme_minimal() +
  theme(plot.title = element_text(hjust = 0.5, size = 14, face = "bold"))

运行后每个单元格的同一行里会显示加粗的得分和对应的评级,完美实现同一注释行的双内容展示。

Python 实现方案(基于Seaborn + Matplotlib)

核心思路:用seaborn.heatmap画基础热力图,然后遍历每个单元格,在同一位置添加双注释内容——可以直接组合成一个文本,也可以分开添加实现不同样式。

步骤1:准备数据和双注释文本

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

np.random.seed(123)
score_data = np.random.randint(60, 101, (4, 4))
categories = ["A", "B", "C", "D"]
groups = ["G1", "G2", "G3", "G4"]

# 生成评级的辅助函数
def get_rating(score):
    if score >= 90:
        return "优秀"
    elif score >= 80:
        return "良好"
    else:
        return "合格"

# 构造每个单元格的双注释文本
annotations = [[f"{score} | {get_rating(score)}" for score in row] for row in score_data]
df = pd.DataFrame(score_data, index=categories, columns=groups)

步骤2:绘制热力图并添加双注释

如果只需要同一行显示两个内容,直接组合文本添加即可:

plt.figure(figsize=(8, 6))
# 绘制基础热力图,关闭默认注释
ax = sns.heatmap(df, cmap="YlGnBu", annot=False, cbar=True, 
                 linewidths=1, linecolor="white")

# 遍历每个单元格,添加双注释
for i in range(len(categories)):
    for j in range(len(groups)):
        ax.text(j + 0.5, i + 0.5, annotations[i][j],
                ha="center", va="center", fontsize=10,
                # 可选:添加半透明背景让文本更清晰
                bbox=dict(facecolor='white', alpha=0.5, edgecolor='none'))

plt.title("带双注释的热力图", fontsize=14, fontweight="bold", pad=20)
plt.xlabel("分组")
plt.ylabel("类别")
plt.tight_layout()
plt.show()

如果想要给两个注释做样式区分(比如得分加粗、评级用灰色),可以分开添加两个文本,调整位置让它们在同一行:

# 替换上面的循环部分
for i in range(len(categories)):
    for j in range(len(groups)):
        score = score_data[i][j]
        rating = get_rating(score)
        # 得分靠左,加粗显示
        ax.text(j + 0.35, i + 0.5, str(score),
                ha="right", va="center", fontsize=10, fontweight="bold")
        # 评级靠右,灰色显示
        ax.text(j + 0.65, i + 0.5, rating,
                ha="left", va="center", fontsize=10, color="gray")

这样就能实现更精细的双注释样式,完全匹配你想要的PPT示例效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:41:45