ggplot stat-ecdf 累积分布自定义最大值

时间:2021-07-08 20:57:01

标签: r ggplot2 dplyr distribution

我有以下格式的 df:

df <- read.table(text="
DAYS    STATUS    ID
 2     Complete   A
 10    Complete   A
 15    Complete   B
 NA    Incomplete A
 NA    Incomplete B
 20    Complete   C", header=TRUE)

我使用以下方法绘制了累积分布:

  ggplot(df,aes(x=DAYS, color=ID)) +
  stat_ecdf(geom = "step")

enter image description here

因为这只是绘制完成的行,所以我想包括几天内具有 NA 的不完整行。通过这样做,每个 ID 的累积分布不会达到 100%,因为某些行没有天数。

ID   PERCENT_COMPLETE
A         .95
B         .55
C         .5

例如,在我的完整数据集中,ID A 的状态为 0.95,因此分配线将在 0.95 处达到最大值,而 B 将在 0.55 处达到最大值。

1 个答案:

答案 0 :(得分:2)

似乎没有任何绘图函数以您想要的方式处理 NA 值。所以我们可以使用 dplyr

以我们想要的方式预先计算值
library(ggplot2)
library(dplyr)
df <- read.table(text="
DAYS    STATUS    ID
 2     Complete   A
 10    Complete   A
 15    Complete   B
 NA    Incomplete A
 NA    Incomplete B
 20    Complete   C", header=TRUE)

incomplete_cdf <- function(x, gmin, gmax) {
  cdf <- rle(sort(na.omit(x)))
  obsx <- cdf$values
  obsy <- cumsum(cdf$lengths)/length(x)
  data.frame(x = c(gmin, obsx, gmax) , y=c(0, obsy, tail(obsy, 1)))
}

df %>% 
  mutate(gmin =min(DAYS, na.rm=TRUE), gmax=max(DAYS, na.rm=TRUE)) %>% 
  group_by(ID) %>% 
  summarize(incomplete_cdf(DAYS, first(gmin), first(gmax)))%>% 
  ggplot(aes(x=x, y=y, color=ID)) +
  geom_step()

enter image description here

相关问题