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

如何在ggplot绘制的柱状图中为阈值线上下的柱子添加对应分类标签

实现方案

你可以先给数据集新增分级标签列,再在ggplot中添加geom_text层渲染标签即可,以下是两种可直接运行的实现方式:

方式1:仅用基础R实现(无需额外安装依赖包)

# 构造原始数据集
data <- data.frame(
  name=letters[1:5],
  value=sample(seq(4,15),5)
)

# 新增分级标签列
data$level <- ifelse(data$value > 10, "high",
                     ifelse(data$value == 10, "normal", "low"))

# 绘图
library(ggplot2)
ggplot(data) +
  geom_bar(aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.7) +
  geom_hline(yintercept = 10, color = "red", linetype = "solid") +
  # 标签层:vjust=-0.2 控制标签在柱子顶部上方,避免重叠
  geom_text(aes(x = name, y = value, label = level), vjust = -0.2)

方式2:配合dplyr使用(逻辑更清晰,避免多层ifelse嵌套)

library(dplyr)
library(ggplot2)

# 构造数据集同时生成分级标签
data <- data.frame(
  name=letters[1:5],
  value=sample(seq(4,15),5)
) %>% 
  mutate(level = case_when(
    value > 10 ~ "high",
    value < 10 ~ "low",
    TRUE ~ "normal" # 剩余等于10的情况匹配normal
  ))

# 绘图
ggplot(data) +
  geom_bar(aes(x=name, y=value), stat="identity", fill="skyblue", alpha=0.7) +
  geom_hline(yintercept = 10, color = "red", linetype = "solid") +
  geom_text(aes(x = name, y = value, label = level), vjust = -0.2)

如果需要调整标签的样式,可在geom_text中新增参数自定义,例如添加size=4调整字号、color="darkred"调整文字颜色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 02:48:03