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

如何在R基础绘图中生成带折线的累积相对频率直方图

生成带折线的累积相对频率直方图(R基础绘图)

你需要生成带有直方图柱体和累积折线的累积相对频率直方图,以下是针对你提供的数据的实现方法:

你的数据

df <- data.frame(foo = c(15, 23, 12, 10, 28, 20, 12, 17, 20, 
                         21, 18, 13, 11, 12, 26, 30,  6, 16,
                         19, 22, 14, 17, 21, 28,  9, 16, 13,
                         11, 16))

实现步骤与代码

核心思路是先获取直方图的统计数据,将绝对频率转换为累积相对频率,再绘图并添加折线:

# 1. 获取直方图的统计信息(仅计算不绘图)
h <- hist(df$foo, plot = FALSE)

# 2. 将绝对频率转换为累积相对频率
total <- length(df$foo)
h$counts <- cumsum(h$counts / total)

# 3. 绘制累积相对频率直方图
plot(h, col = "hotpink", 
     main = "累积相对频率直方图",
     xlab = "foo变量值", 
     ylab = "累积相对频率")

# 4. 添加累积折线(从原点(0,0)开始连接各柱中点)
lines(c(0, h$mids), c(0, h$counts), col = "blue", lwd = 2)
# 若需要阶梯状折线,可添加type="s"参数:
# lines(c(0, h$mids), c(0, h$counts), col = "blue", lwd = 2, type = "s")

关键说明

  • hist(..., plot=FALSE)会返回包含分组区间、频率、柱中点等信息的列表,方便我们修改数据后再绘图
  • 累积相对频率的计算逻辑:先将每组的绝对频率除以总样本数得到相对频率,再用cumsum()累加得到累积值
  • lines()函数从(0,0)开始绘制折线,和目标图的折线起始位置一致,lwd=2可以让折线更醒目

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 17:32:47