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

如何将ggplot::geom_area()的图例嵌入对应填充区域?

将ggplot堆叠面积图的图例嵌入对应填充区域

要实现把图例直接嵌入到各填充区域的效果,我们可以放弃默认图例,转而在每个堆叠区域的合适位置添加文本标签来替代,具体实现步骤如下:

1. 加载依赖包

library(ggplot2)
library(dplyr)

2. 准备/处理数据

以模拟的年份-类别数据为例(对应原图表结构),先计算每个堆叠区域的中心坐标,用来放置标签:

# 模拟示例数据
df <- data.frame(
  Year = rep(2010:2020, 3),
  Category = rep(c("A", "B", "C"), each = 11),
  Value = c(20,25,30,32,35,38,40,42,45,48,50,
            15,18,22,25,28,30,32,35,38,40,42,
            10,12,15,18,20,22,25,28,30,32,35)
)

# 计算每个堆叠区域的中心位置
df_label <- df %>%
  arrange(Year, Category) %>%
  group_by(Year) %>%
  mutate(
    y_lower = cumsum(Value) - Value,
    y_upper = cumsum(Value),
    y_mid = (y_lower + y_upper)/2
  ) %>%
  ungroup() %>%
  # 选择中间年份作为标签放置的x位置
  filter(Year == 2015)

3. 绘制带嵌入式标签的堆叠面积图

ggplot(df, aes(x = Year, y = Value, fill = Category)) +
  geom_area(position = "stack") +
  # 在各区域中心添加类别标签
  geom_text(data = df_label, aes(x = Year, y = y_mid, label = Category),
            color = "white", fontface = "bold", size = 4) +
  # 关闭默认图例
  theme(legend.position = "none") +
  labs(x = "年份", y = "数值") +
  scale_fill_brewer(palette = "Set2")

说明

  • 可以根据需求调整标签的x位置(比如改为Year == 2020放在区域右侧),或者修改文本的颜色、大小、字体样式;
  • 如果使用真实数据,只需替换df部分的数据集,保持后续计算逻辑一致即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:57:10