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

如何在ggplot的barplot中标记对应中位数的条形

条形图标注中位数中心实现方案

你需要实现两种标记偶数个中心中数值更高的中位数中心的效果,本示例中目标中心为Centre 6,以下是可直接运行的完整实现代码:

完整代码(同时实现两种标记效果)

library(ggplot2)

# 构造基础数据
Centre <- paste("Centre", 1:10, sep= " ")
Value <- c(10, 23, 27, 50, 60, 71, 88, 102, 110, 113)
mydata <- data.frame(Centre, Value)
# 固定中心排序,避免因子默认按字母排序错乱
mydata$Centre <- factor(mydata$Centre, levels = Centre)

# 自动定位数值更高的中位数中心(适配任意数量中心的场景)
mydata_sorted <- mydata[order(mydata$Value), ]
n <- nrow(mydata_sorted)
target_centre <- mydata_sorted$Centre[ceiling(n/2)]
mydata$is_median_target <- ifelse(mydata$Centre == target_centre, "中位数中心", "其他中心")

# 绘图
ggplot(mydata, aes(x = Centre, y = Value)) +
  # 条形图,按是否为中位数中心映射填充色
  geom_col(aes(fill = is_median_target)) +
  # 自定义填充色,高亮中位数中心
  scale_fill_manual(values = c("其他中心" = "gray50", "中位数中心" = "darkred")) +
  # 绘制穿过中位数中心的水平线(因使用coord_flip翻转坐标轴,此处对应目标分类的位置)
  geom_hline(yintercept = which(levels(mydata$Centre) == target_centre), color = "blue", linewidth = 1, linetype = "dashed") +
  # 翻转坐标轴
  coord_flip() +
  # 可选:调整图例名称
  labs(fill = "中心类型")

效果说明

  • 条形高亮:目标Centre 6的条形会显示为醒目的深红色,其余为灰色
  • 水平线:蓝色虚线会水平穿过Centre 6对应的条形位置,清晰标记中位数中心所在行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:24:04