2017-03-04 178 views
2

这里是我的代码和我的输出(CDF):如何绘制R中的互补累积分布函数(CCDF)(最好在ggplot中)?

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

您可以使用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

0

在一步一步,你也可以这样做:

# 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