首页 > 解决方案 > 在 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()

拟合并绘制系列的分布x。结果图是: 在此处输入图像描述 包似乎不支持瑞利分布statsMASS如何将之前的代码扩展到瑞利分布?

标签: rcurve-fitting

解决方案


在下面的代码中,我首先重新创建 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()

推荐阅读