r语言绘制直方图,密度估计曲线,经验分布图和QQ图,并将密度估计曲线与正太密度曲线做比较,将经验分布曲线与正太分布曲线做比较
时间: 2024-11-20 10:40:48 浏览: 12
在R语言中,绘制图形是数据可视化的重要部分。以下是创建这几种常见图表的简要步骤:
1. **直方图 (Histogram)**:
使用`hist()`函数,例如:
```R
data <- c(rnorm(50), rpois(50, 10)) # 示例数据
hist(data, main = "直方图", xlab = "数值", ylab = "频数")
```
2. **密度估计曲线 (Kernel Density Estimation, KDE)**:
可以用`density()`函数配合`plot()`或`lines()`展示:
```R
density_data <- density(data)
plot(density_data, type = "l", main = "密度估计曲线", xlab = "数值", ylab = "概率密度")
```
或者加上原点正态分布对比:
```R
norm_density <- dnorm(data, mean = mean(data), sd = sd(data))
lines(density_data$x, norm_density, col = "red", lty = 2, lwd = 2, legend = "正态密度")
```
3. **经验分布图 (Empirical Cumulative Distribution Function, ECDF)**:
`ecdf()`函数生成ECDF,然后`plot()`显示:
```R
ecdf_plot <- ecdf(data)
plot(ecdf_plot, main = "经验分布图", xlab = "数值", ylab = "累积分布比例")
```
4. **QQ图 (Quantile-Quantile Plot)**:
`qqline()`函数用于添加正态QQ线到散点图上:
```R
qq_data <- qplot(qdata = quantile(data, probs = seq(0, 1, length.out = 100)),
ydata = qnorm(seq(0, 1, length.out = 100)), geom = "pointrange",
main = "QQ图", xlab = "理论分位数", ylab = "样本分位数")
abline(a = 0, b = 1, col = "red") # 添加正态直线
```
通过以上操作,你可以直观地对比数据的分布特性以及它们是否接近正态分布。
阅读全文