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

如何在R语言geom_bar分组柱状图底部添加红线(非geom_hline方法)

分组柱状图添加底部红线(不使用geom_hline())

要给你的分组柱状图底部添加红线且不使用geom_hline(),可以通过geom_segment()或annotate()绘制线段来实现,以下是两种可行方案:

方案一:使用geom_segment()

直接在绘图代码中加入线段绘制逻辑,精准控制红线位置:

sample <- c("AA", "AA", "AA", "BB", "BB", "BB")
location<- c("Washington", "Mongolia", "Egypt", "Washington", "Mongolia", "Egypt" )
value <- c(0.03, 0.06, 0.02, 0.0051, 0.0082, 0.003)
data <- data.frame(sample, location, value)

ggplot(data, aes(fill=location, y=value, x=sample)) + 
  geom_bar(position="dodge", stat="identity", color="black")+
  # 绘制底部红线
  geom_segment(aes(x = 0.5, xend = 2.5, y = 0, yend = 0), 
               color = "red", size = 1)+
  theme_classic()+
  scale_fill_grey() +
  scale_x_discrete(limits=c("BB", "AA"))

参数说明:

  • x=0.5和xend=2.5:对应x轴两个类别(BB、AA)的外侧边界,确保红线覆盖整个图表底部区域
  • y=yend=0:固定线段在y轴底部位置
  • size:可根据需求调整红线粗细

方案二:使用annotate()

通过annotate()添加线段,无需映射美学属性,写法更简洁:

sample <- c("AA", "AA", "AA", "BB", "BB", "BB")
location<- c("Washington", "Mongolia", "Egypt", "Washington", "Mongolia", "Egypt" )
value <- c(0.03, 0.06, 0.02, 0.0051, 0.0082, 0.003)
data <- data.frame(sample, location, value)

ggplot(data, aes(fill=location, y=value, x=sample)) + 
  geom_bar(position="dodge", stat="identity", color="black")+
  # 绘制底部红线
  annotate("segment", x=0.5, xend=2.5, y=0, yend=0, color="red", size=1)+
  theme_classic()+
  scale_fill_grey() +
  scale_x_discrete(limits=c("BB", "AA"))

两种方法都能实现底部红线效果,且完全符合不使用geom_hline()的要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 14:01:40