r - 在 R 中拟合瑞利
问题描述
这段代码
library(ggplot2)
library(MASS)
# Generate gamma rvs
x <- rgamma(100000, shape = 2, rate = 0.2)
den <- density(x)
dat <- data.frame(x = den$x, y = den$y)
ggplot(data = dat, aes(x = x, y = y)) +
geom_point(size = 3) +
theme_classic()
# Fit parameters (to avoid errors, set lower bounds to zero)
fit.params <- fitdistr(estimate, "gamma", lower = c(0, 0))
# Plot using density points
ggplot(data = dat, aes(x = x,y = y)) +
geom_point(size = 3) +
geom_line(aes(x=dat$x, y=dgamma(dat$x,fit.params$estimate["shape"], fit.params$estimate["rate"])),
color="red", size = 1) +
theme_classic()
解决方案
在下面的代码中,我首先重新创建 vector x
,这次设置 RNG 种子,以使结果可重现。dat
然后,还重新创建了仅包含该向量的 data.frame 。
Gamma 和 Rayleigh 分布的密度函数x
通过首先估计它们的参数和来拟合直方图stat_function
。
library(ggplot2)
library(MASS)
library(extraDistr) # for the Rayleigh distribution functions
# Generate gamma rvs
set.seed(2020)
x <- rgamma(100000, shape = 2, rate = 0.2)
dat <- data.frame(x)
# Fit parameters (to avoid errors, set lower bounds to zero)
fit.params <- fitdistr(dat$x, "gamma", lower = c(0, 0))
ggplot(data = dat, aes(x = x)) +
geom_histogram(aes(y = ..density..), bins = nclass.Sturges(x)) +
stat_function(fun = dgamma,
args = list(shape = fit.params$estimate["shape"],
rate = fit.params$estimate["rate"]),
color = "red", size = 1) +
ggtitle("Gamma density") +
theme_classic()
fit.params.2 <- fitdistrplus::fitdist(dat$x, "rayleigh", start = list(sigma = 1))
fit.params.2$estimate
ggplot(data = dat, aes(x = x)) +
geom_histogram(aes(y = ..density..), bins = nclass.Sturges(x)) +
stat_function(fun = drayleigh,
args = list(sigma = fit.params.2$estimate),
color = "blue", size = 1) +
ggtitle("Rayleigh density") +
theme_classic()
要绘制问题中的点和线,而不是直方图,请使用下面的代码。
den <- density(x)
orig <- data.frame(x = den$x, y = den$y)
ggplot(data = orig, aes(x = x)) +
geom_point(aes(y = y), size = 3) +
geom_line(aes(y = dgamma(x, fit.params$estimate["shape"], fit.params$estimate["rate"])),
color="red", size = 1) +
geom_line(aes(y = drayleigh(x, fit.params.2$estimate)),
color="blue", size = 1) +
theme_classic()
推荐阅读
- jquery - 特定类的 jQuery 选择器
- hyperledger-fabric - 出现错误:http:从 Hyperledger Composer 中的事务处理器函数读取已关闭的响应正文
- mysql - Mysql我如何对两个表进行sql并从第二个开始计算groupid
- java - flink 是否在批处理模式下即时减少
- java - 如何预测 StackOverFlow?
- api - Salesforce Analytics API 运行用户
- python - 当 parse_dates 失败时,熊猫会掉行
- python - 如何通过 selenium python 从所有页面获取数据
- php - 添加额外的身份验证变量表单用户表社区身份验证
- css - 观察所有 sass 文件的变化并将它们保存在一个 css 文件中