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

如何在ggplot2绘制的图表中根据y轴数值叠加分面(facet)标签

实现方案

你需要的重叠分类标注不需要使用分面拆分画布,直接通过geom_rect绘制分类区间条+geom_text添加标签即可实现。另外你原代码中的分类判定逻辑存在优先级问题,会导致280-350分钟的区间无法被识别为Good分类,此处直接按你给出的固定区间做标注更适配重叠分类的需求。

完整可运行代码

library(ggplot2)

# 原始造数逻辑
Product <- c("A", "B")
Color <- c("C1", "C2")
Time <- seq(10, 430, 60)

df <- expand.grid(Time = Time,
                  Color = Color,
                  Product = Product)

df$Fill_factor <- seq(1, 32, 1)

# 绘图逻辑
ggplot(data = df,
       aes(x = Product,
           y = Time,
           fill = Fill_factor)) +
  geom_tile() +
  geom_text(aes(label = Fill_factor),
            size = 2.5) +
  # 绘制Bad分类标注条
  geom_rect(aes(xmin = -Inf, xmax = Inf, ymin = -5, ymax = 15), 
            fill = "red", alpha = 0.2, inherit.aes = FALSE) +
  geom_text(aes(x = 1.5, y = 10, label = "Bad"), 
            size = 3, fontface = "bold", inherit.aes = FALSE) +
  # 绘制Regular分类标注条
  geom_rect(aes(xmin = -Inf, xmax = Inf, ymin = 145, ymax = 355), 
            fill = "yellow", alpha = 0.2, inherit.aes = FALSE) +
  geom_text(aes(x = 1.5, y = 250, label = "Regular"), 
            size = 3, fontface = "bold", inherit.aes = FALSE) +
  # 绘制Good分类标注条
  geom_rect(aes(xmin = -Inf, xmax = Inf, ymin = 275, ymax = 435), 
            fill = "green", alpha = 0.2, inherit.aes = FALSE) +
  geom_text(aes(x = 1.5, y = 350, label = "Good"), 
            size = 3, fontface = "bold", inherit.aes = FALSE) +
  facet_grid(~ Color) +
  scale_y_continuous(breaks = seq(10, 430, 60))

效果说明

  • 三个分类的半透明条会重叠显示在热力图对应时间区间上,重叠区域会自动混合颜色,匹配分类重叠需求
  • 分类标签固定在对应区间的居中位置,不会拆分画布
  • 保留原有按Color分面的逻辑,热力图的数值显示也完全保留

内容的提问来源于stack exchange,提问作者Daniel Valencia C.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 04:06:02