You need to enable JavaScript to run this app. R语言绘制多组别密度山脊图并添加均值斜率线的实现方法
优惠活动
大模型
产品
解决方案
定价
更多

R语言绘制多组别密度山脊图并添加均值斜率线的实现方法

实现方法

你需要先计算每个分组的y值均值,再额外叠加折线和点图层即可,注意要关闭图层的美学映射继承避免报错。

完整可运行代码

library(tidyverse)
library(ggridges)

# 生成示例数据
data1 <- data.frame(x1 = c(rep(1,50), rep(2,50), rep(3,50), rep(4,50), rep(5,50)),
                    y1 = c(rnorm(50,10,1), rnorm(50,15,2), rnorm(50,20,3), rnorm(50,25,3), rnorm(50,30,4)))
data1$x1 <- as.factor(data1$x1)

# 计算每个分组的y均值
mean_data <- data1 %>%
  group_by(x1) %>%
  summarise(mean_y = mean(y1), .groups = "drop")

# 绘图
ggplot(data1, aes(x = y1, y = x1, fill = 0.5 - abs(0.5 - stat(ecdf)))) +
  stat_density_ridges(geom = "density_ridges_gradient", calc_ecdf = TRUE) +
  scale_fill_viridis_c(name = "Tail probability", direction = -1) +
  # 添加均值连线
  geom_line(data = mean_data, aes(x = mean_y, y = as.numeric(x1)), 
            color = "red", linewidth = 1.2, inherit.aes = FALSE) +
  # 添加均值标记点,可按需删除
  geom_point(data = mean_data, aes(x = mean_y, y = as.numeric(x1)), 
             color = "darkred", size = 3, inherit.aes = FALSE)

关键说明

  • 用as.numeric(x1)是因为分类变量在ggplot坐标轴的实际位置为对应的整数值,刚好匹配各条山脊图的纵向位置,能保证连线正好穿过每组密度图的中心
  • inherit.aes = FALSE必须设置,否则折线图层会继承全局的fill映射,找不到stat(ecdf)变量导致报错
  • 折线的颜色、粗细、点的样式都可以根据需求自行调整

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 09:48:01