简体   繁体   English

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

[英]How to plot a Complementary Cumulative Distribution Function (CCDF) in R (preferbly in ggplot)?

Here is my code and my output (CDF):这是我的代码和我的输出(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()

在此处输入图片说明

I'd like to plot a CCDF function, what is the "inverse" of the CDF function: CCDF(x)=1-CDF(x).我想绘制一个 CCDF 函数,什么是 CDF 函数的“逆”:CCDF(x)=1-CDF(x)。 I cannot find any sources about this problem.我找不到有关此问题的任何来源。 Is there any easy way?有什么简便的方法吗?

You can use ggplot_build to extract the data used for the plot and then modify it:您可以使用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()

在此处输入图片说明

In a step-by-step, you can also do this:您还可以分步执行以下操作:

# 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")

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM