问题
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