如何在R中绘制互补累积分布函数(CCDF)(最好是在ggplot中)?

时间:2017-03-04 18:38:33

标签: r ggplot2 cdf ecdf

这是我的代码和输出(CDF):

install.packages("ggplot2")
library(ggplot2)


chol <- read.table(url("http://assets.datacamp.com/blog_assets/chol.txt"), header = TRUE)
df <- data.frame(x = chol$AGE)
ggplot(df, aes(x)) + stat_ecdf()

enter image description here

我想绘制一个CCDF函数,CDF函数的“逆”是什么:CCDF(x)= 1-CDF(x)。我找不到关于这个问题的任何消息来源。有什么简单的方法吗?

2 个答案:

答案 0 :(得分:3)

您可以使用ggplot_build提取用于绘图的数据,然后对其进行修改:

p  <- ggplot(df, aes(x)) + stat_ecdf()
pg <- ggplot_build(p)$data[[1]]
ggplot(pg, aes(x = x, y = 1-y )) + geom_step()

enter image description here

答案 1 :(得分:1)

您可以逐步执行此操作:

# load data
  chol <- read.table(url("http://assets.datacamp.com/blog_assets/chol.txt"), header = TRUE)


# get the ecdf - Empirical Cumulative Distribution Function of v
  my_ecdf <- ecdf( chol$AGE )

# now put the ecdf and its complementary in a data.frame
  df <- data.frame( x = sort(chol$AGE),
                    y = 1-my_ecdf(sort(chol$AGE) ))

# plot
  ggplot(data=df, aes(x, y) ) +
    geom_line() +
    geom_point(color="red")

enter image description here