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

如何使用ggplot2在指定geom_area分组区域之间添加空白间隔

想要在不同type的面积区域之间添加空白间隔,只需要在两个type的时间交界处插入一条对应前序type、value为0的记录即可,完整实现代码如下:

library(dplyr)
library(ggplot2)

# 加载补充数据集
df <- structure(list(date = c("2021-07-31", "2021-08-31", "2021-09-07", 
"2021-09-14", "2021-09-21", "2021-09-30", "2021-10-7", "2021-10-14", 
"2021-10-21", "2021-10-31", "2021-11-30", "2021-12-31", "2022-1-31", 
"2022-2-28"), value = c(190.3, 174.9, 163.2, 168.4, 168.6, 168.2, 
163.5, 161.6, 172.9, 166.5, 175.2, 197.7, 212.1, 177.9), type = c(1L, 
1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L)), class = "data.frame", row.names = c(NA, -14L))

# 预处理数据格式
df$date <- as.Date(df$date)
df$type <- as.factor(df$type)

# 生成间隔行
type_start <- df %>% 
  group_by(type) %>% 
  slice_head(n = 1) %>% 
  ungroup()

gap_rows <- type_start %>% 
  mutate(type = lag(type),
         date = date - 1,
         value = 0) %>% 
  filter(!is.na(type))

# 合并数据并排序
df_final <- bind_rows(df, gap_rows) %>% 
  arrange(date, type)

# 绘图
ggplot(df_final, aes(x=date, y=value, group=type, color = type, fill = type)) + 
  geom_area(alpha=0.4, position = "identity") +
  scale_color_manual(values=c("1" = "gray", "2" = "red", "3" = "blue"), 
                     aesthetics = c("color", "fill"), name = "type") +
  theme_bw()

上述代码在相邻type的交界处插入了value为0的过渡记录,绘图时该位置的面积会落到y轴基线,自然形成空白间隔。如果需要在所有相邻type之间都加间隔,不需要修改逻辑,代码已经自动支持所有相邻分组的间隔生成。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:06:05