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

如何在ggplot柱状图的geom_line层上方添加标签?

解决ggplot折线标签位置问题

我用ggplot绘制了叠加折线的柱状图,希望把标签放在红色移动平均线的上方,而不是柱状图顶部。当前使用的代码如下:

ggplot(media_movel, aes(x=SE_PRI_SIN, y=n, fill= " ", group = 1)) +
  geom_bar(stat='identity', position='dodge', color = "black", fill = "skyblue4") +
  geom_line(data = media_movel, aes(y = media, color = "MÉDIA MÓVEL"), size = 0.75) +
  geom_text(aes(label= media), hjust= 0.5, vjust = -1, size=3, color= "black")+
  scale_y_continuous(limits = c(0, max(media_movel$n)+250), expand = expansion(mult = c(0, .1)))+
  labs(fill = " ", x = "Semana Epidemiológica", y = "Número de Casos") +
  scale_colour_manual(" ", values=c("CASOS" = "skyblue4", "MÉDIA MÓVEL" = "red"))+
  theme_minimal(base_size = 10)+
  theme(legend.position = "bottom", axis.line = element_line(colour = "black"),
        axis.text.x=element_text(angle = 90, vjust = 0.5, colour="black"), 
        axis.text.y=element_text(colour="black"))

可复现数据:

data <- data.frame(SE_PRI_SIN= c("SE 29", "SE 30", "SE 31", "SE 32", "SE 33","SE 34", "SE 35", "SE 36",
                                 "SE 37", "SE 38"),
                   n = c(5, 10, 28, 33, 78, 19, 50, 88, 97, 7824),
                   media_movel = c(494.5, 525.5, 568, 645, 700, 618, 476.5, 370.5, 299.5, 4994))

解决方案

核心问题是当前geom_text继承了全局映射的y=n,导致标签默认附着在柱状图顶部。要让标签移到折线上方,只需调整geom_text的y轴映射,并修正代码里的笔误:

  1. 修正列名笔误:代码里的media是错的,数据中移动平均线的列名是media_movel,需要统一替换。
  2. 指定标签的y轴位置:在geom_text中明确设置y = media_movel,覆盖全局的y=n,让标签的纵向位置对应折线高度。
  3. 微调标签偏移:调整vjust参数(比如从-1改为-0.5),让标签刚好落在折线正上方,数值可根据视觉效果调整。

修正后的完整代码:

ggplot(media_movel, aes(x=SE_PRI_SIN, y=n, fill= " ", group = 1)) +
  geom_bar(stat='identity', position='dodge', color = "black", fill = "skyblue4") +
  geom_line(aes(y = media_movel, color = "MÉDIA MÓVEL"), size = 0.75) +
  geom_text(aes(y = media_movel, label= media_movel), hjust= 0.5, vjust = -0.5, size=3, color= "black")+
  scale_y_continuous(limits = c(0, max(media_movel$n)+250), expand = expansion(mult = c(0, .1)))+
  labs(fill = " ", x = "Semana Epidemiológica", y = "Número de Casos") +
  scale_colour_manual(" ", values=c("CASOS" = "skyblue4", "MÉDIA MÓVEL" = "red"))+
  theme_minimal(base_size = 10)+
  theme(legend.position = "bottom", axis.line = element_line(colour = "black"),
        axis.text.x=element_text(angle = 90, vjust = 0.5, colour="black"), 
        axis.text.y=element_text(colour="black"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 08:54:20