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

R语言ggplot2图表中如何在x轴上方添加x变量的频数分布刻度线

R ggplot2 x轴上方展示变量分布实现方案

方案1:快速添加观测点标记(和参考图效果一致)

直接在原有折线图基础上叠加geom_rug图层,即可在x轴顶部标记所有lstat的观测位置:

library(ggplot2)
library(mlbench)

data(BostonHousing)

ggplot(data = BostonHousing) +
  geom_line(aes(x = lstat, y = medv)) +
  # sides = "t" 表示标记放置在x轴顶部
  geom_rug(aes(x = lstat), sides = "t", color = "#666666", alpha = 0.5)

你可以调整alpha参数解决点重叠的问题,修改color自定义标记颜色。

方案2:拼接独立分布图层(展示完整频数分布)

如果需要展示更清晰的直方图/密度分布,可使用patchwork包将分布图和折线图上下拼接,共用x轴完全对齐:

library(ggplot2)
library(mlbench)
library(patchwork)

data(BostonHousing)

# 顶部lstat频数分布直方图
p_top <- ggplot(BostonHousing, aes(x = lstat)) +
  geom_histogram(bins = 30, fill = "skyblue", alpha = 0.7) +
  # 移除冗余轴元素,保持和下图对齐
  theme_void() +
  theme(plot.margin = margin(b = 0))

# 底部核心折线图
p_main <- ggplot(data = BostonHousing) +
  geom_line(aes(x = lstat, y = medv)) +
  theme(plot.margin = margin(t = 0))

# 上下拼接,设置高度比例为1:4
p_top / p_main + plot_layout(heights = c(1, 4))

如果需要换成密度图,只需要把geom_histogram替换为geom_density即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 08:18:02