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

如何为ggplot2的stat_function绘图添加十分位数断点?

用stat_function绘制带十分位数分区的理论分布密度图

要实现用stat_function绘制平滑的理论分布曲线,同时添加十分位数的分区填充和轴断点,无需依赖模拟数据,可按以下方式实现:

核心思路

直接使用分布的理论分位数(而非模拟数据分位数),结合stat_function生成的计算数据完成分区填充与轴断点设置,既能保证曲线平滑,又能方便切换分布和参数。

完整代码

library(ggplot2)

# 配置分布参数与十分位数
rate <- 3
probs <- seq(0, 1, 0.1)
# 计算指数分布的理论十分位数
quantiles <- qexp(probs, rate = rate)

# 绘图
ggplot(data = data.frame(x = c(0, qexp(0.999, rate = rate))), aes(x)) +
  # 绘制理论密度曲线
  stat_function(fun = dexp, args = list(rate = rate), n = 1001, linewidth = 1) +
  # 按十分位数分区填充面积
  stat_function(
    fun = dexp, args = list(rate = rate), n = 1001,
    geom = "ribbon", aes(
      ymin = 0, ymax = after_stat(y),
      fill = factor(findInterval(after_stat(x), quantiles))
    ),
    alpha = 0.7
  ) +
  # 设置x轴断点为十分位数
  scale_x_continuous(breaks = quantiles) +
  # 配置填充色并隐藏图例
  scale_fill_brewer(palette = "Blues", guide = "none") +
  theme_minimal()

关键说明

  1. 理论分位数计算:用qexp直接计算指数分布的十分位数,避免模拟数据的随机性,与stat_function的理论分布完全匹配
  2. 灵活切换分布:如果要更换其他分布,只需修改3处:
    • 将fun = dexp改为对应密度函数(如dnorm、dgamma)
    • 将args = list(rate = rate)改为对应参数(如mean=0, sd=1)
    • 将qexp改为对应分位数函数(如qnorm、qgamma)
  3. 平滑保障:设置n=1001让stat_function生成足够多的点,确保曲线和填充的平滑度
  4. 分区填充逻辑:通过after_stat(x)获取stat_function生成的x值,用findInterval判断其所属的十分位数区间,以此作为填充分组依据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 08:15:35