How to plot a CDF functon from PDF in R

倾然丶 夕夏残阳落幕 提交于 2021-01-29 03:22:09

问题


I have the following function:

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);
}

How can I plot it's CDF function on the interval [0,10]?


回答1:


To add a bit accuracy to @Martin Schmelzer's answer. A cummulative distribution function(CDF)

evaluated at x, is the probability that X will take a value less than or equal to x

So to get CDF from Probability Density Function(PDF), you need to integrate on 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")




回答2:


Try

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)




回答3:


Just adding up on the previous answers and using 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) 



来源:https://stackoverflow.com/questions/41317876/how-to-plot-a-cdf-functon-from-pdf-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!