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

如何避免ggridridges密度脊图中均值与中位数线重叠?

解决ggridridges均值线重叠问题

你遇到的均值线重叠问题,根源是两次调用geom_density_ridges_gradient时,第二个图层会重新生成全部分组的密度曲线框架,导致均值线跨子图乱跑重叠。最稳妥的解决办法是提前算出每个月份的均值和中位数,用geom_vline单独加线,避免重复绘制密度图层。

修改后的代码:

library(ggridges)
library(ggplot2)
library(dplyr)

# 先算出每个月份的温度均值和中位数
month_temp_stats <- lincoln_weather %>%
  group_by(Month) %>%
  summarise(
    mean_temp = mean(`Mean Temperature [F]`, na.rm = TRUE),
    median_temp = median(`Mean Temperature [F]`, na.rm = TRUE)
  )

ggplot(lincoln_weather, aes(x = `Mean Temperature [F]`, y = Month, fill = stat(x))) +
  # 画主密度脊图,包含中位数线和散点
  geom_density_ridges_gradient(
    alpha = 0.8,
    color = "black",
    scale = 2,
    rel_min_height = 0,
    jittered_points = TRUE,
    position = position_points_jitter(width = 0.05, height = 0),
    point_shape = "|",
    point_size = 3,
    point_alpha = 1,
    quantile_lines = TRUE,
    vline_color = "green",
    quantile_fun = median
  ) +
  # 加均值竖线,每条线对应自己的月份子图
  geom_vline(
    data = month_temp_stats,
    aes(xintercept = mean_temp),
    color = "blue",
    linetype = "solid"
  ) +
  scale_fill_viridis_c(name = "Temp. [F]", option = "C") +
  labs(title = "Temperatures in Lincoln NE in 2016")

关键改动说明:

  • 用dplyr按月份分组计算均值和中位数,生成专门的统计数据集month_temp_stats
  • 删掉第二次geom_density_ridges_gradient调用,改用geom_vline加均值线,通过data参数绑定统计数据,确保每条线精准对应所属月份的子图
  • 彻底避免重复绘制密度曲线框架,从根源解决线条重叠问题

如果非要用两次geom_density_ridges_gradient,可以在第二个图层里设置只画分位数线、隐藏密度曲线:

# 备选方案:两次调用geom_density_ridges_gradient
ggplot(lincoln_weather, aes(x = `Mean Temperature [F]`, y = Month, fill = stat(x))) +
  geom_density_ridges_gradient(
    alpha = 0.8,
    color = "black",
    scale = 2,
    rel_min_height = 0,
    jittered_points = TRUE,
    position = position_points_jitter(width = 0.05, height = 0),
    point_shape = "|",
    point_size = 3,
    point_alpha = 1,
    quantile_lines = TRUE,
    vline_color = "green",
    quantile_fun = median
  ) +
  geom_density_ridges_gradient(
    scale = 2,
    rel_min_height = 0,
    quantile_lines = TRUE,
    vline_color = "blue",
    fill = NA,
    color = NA,  # 隐藏密度曲线的轮廓线
    draw = FALSE,  # 不绘制密度脊的主体部分
    quantile_fun = mean
  ) +
  scale_fill_viridis_c(name = "Temp. [F]", option = "C") +
  labs(title = "Temperatures in Lincoln NE in 2016")

不过这种方法不如第一种直观,优先推荐提前统计加geom_vline的方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 04:54:16