如何在R中用PDF绘制CDF功能

时间:2016-12-25 00:27:45

标签: r statistics

我有以下功能:

fx <- function(x) {
  if(x >= 0 && x < 3) {
    res <-  0.2;
  } else if(x >=3 && x < 5) {
    res <- 0.05;
  } else if(x >= 5 && x < 6) {
    res <-  0.15;
  } else if(x >= 7 && x < 10) {
    res <-  0.05;
  } else {
    res <- 0;
  }

  return(res);
}

如何在[0,10]间隔内绘制CDF函数?

3 个答案:

答案 0 :(得分:5)

尝试

fx   <- Vectorize(fx)
grid <- 0:10
p    <- fx(grid)
cdf  <- cumsum(p)

plot(grid, cdf, type = 'p', ylim = c(0, 1), col = 'steelblue',
     xlab = 'x', ylab = expression(F(x)), pch = 19, las = 1)
segments(x0 = grid, x1 = grid + 1, y0 = cdf)
segments(x0 = grid + 1, y0 = c(cdf[-1], 1), y1 = cdf, lty = 2)

enter image description here

答案 1 :(得分:2)

为@Martin Schmelzer的答案添加一点准确性。 累积分布函数(CDF)

  

在x处评估,是X取小于的值的概率   或等于x

因此,要从概率密度函数(PDF)获取CDF,您需要在PDF上集成:

fx <- Vectorize(fx)
dx <- 0.01
x <- seq(0, 10, by = dx)
plot(x, cumsum(fx(x) * dx), type = "l", ylab = "cummulative probability", main = "My CDF")

enter image description here

答案 2 :(得分:0)

只需添加以前的答案并使用ggplot

# cdf
Fx <- function(x, dx) {
  cumsum(fx(x)*dx)
}

fx <- Vectorize(fx)
dx <- 0.01
x <- seq(0, 10, dx)
df <- rbind(data.frame(x, value=fx(x), func='pdf'), 
            data.frame(x, value=Fx(x, dx), func='cdf'))
library(ggplot2)
ggplot(df, aes(x, value, col=func)) + 
  geom_point() + geom_line() + ylim(0, 1) 

enter image description here