【问题标题】:Plot discrete density for a given cumulative distribution function绘制给定累积分布函数的离散密度
【发布时间】:2019-09-20 12:16:11
【问题描述】:

给定一个离散累积分布函数,形式如下:

set.seed(1)
x  <- rnorm(100,0,1)
y  <- ecdf(x)(sort(x))
cdf <- data.table(x=sort(x),y=y)

str(cdf)
   Classes ‘data.table’ and 'data.frame':   100 obs. of  2 variables:
   $ x: num  -2.21 -1.99 -1.8 -1.52 -1.47 ...
   $ y: num  0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1 ...
   - attr(*, ".internal.selfref")=<externalptr> 

我现在想用 ggplot 绘制离散密度。具体来说,我想要条形图/直方图,其中

  1. 条形的宽度由 x 的差值定义,条形分别从一个 x 到下一个 x
  2. 高度由累积概率的差值给出

所以它就像一个阶梯函数

【问题讨论】:

    标签: r ggplot2 data.table


    【解决方案1】:

    像这样?我不确定您所说的“高度是由累积概率的差异给出的”是什么意思,因为对于所有 x 来说,这似乎都是 0.01。

    library(dplyr)
    cdf %>%
      arrange(x) %>%
      # The "default =" term below lets us assign a leftmost width (and thereby 
      #  display something for 100%) even though lead(x) is NA for the last row.
      mutate(x_next = lead(x, default = max(x) + 0.05),
             y_change = lead(y) - y) %>% 
      ggplot(aes(xmin = x, xmax = x_next,
                 ymin = 0, ymax = y)) +
      geom_rect()
    

    【讨论】:

      最近更新 更多