2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CCDF(相補累積分布関数)をecdf()とggplot2でかんたんに書く

2
Last updated at Posted at 2019-10-22

CCDFとは

CCDF (Complementary Cumulative Distribution Function)。Wiki(En)もしくはWiki(Jp)を読む。

次のようなポアソン分布に従う頻度データ(カウントデータ)のCCDFを両対数グラフ上にggplot2で書きたい。

data <- tibble(count = rpois(n = 1000, lambda = 20))
> data
# A tibble: 1,000 x 1
   count
   <int>
 1    12
 2    19
 3    15
 4    14
 5    17
 6    18
 7    13
 8    22
 9    14
10    19
# … with 990 more rows

1: stat_ecdf()でプロットし、生成されたdata.frameをもう一回プロットする

"CCDF ggplot"でググると、まずggplot2にデフォルトで用意されているstat_ecdf()で経験的累積分布関数ECDFをかき、そこからggplot_build()を使って値を取り出してこい、という方法がまず出てくる

ECDFがどういう見た目になるか

stat_ecdf plot}
data %>% 
  ggplot(
    aes(
      x = count
    )
  ) +
  stat_ecdf(pad = FALSE)

ecdf.png

このプロットからデータフレームを抽出する。

extract data.frame from stat_ecdf.r}
data_ecdf <- 
  ggplot_build(
    data %>% 
      ggplot(
        aes(
          x = count
        )
      ) +
      stat_ecdf(pad = FALSE)
  )$data[[1]]

読みにくいったらありゃしない。さらにここから両対数グラフにプロットするには

stat_ecdf.r}
data_ecdf %>% 
  ggplot(aes(x = count, y = 1 - y)) +
  geom_point() +
  scale_x_continuous(trans = "log10", breaks = 10^(0:10))+
  scale_y_continuous(trans = "log10", breaks = 10^(0:-10)) 

とする必要がある。
ccdf.png

これらをいっぺんに行うにはecdf()を使う。

2: ecdf()で値を取り出す

先述のstackoverflowの2つ目の回答を改良する。{stats}にはいっているecdf()を用いて、

ecdf.r}
data %>%
  ggplot(aes(x = count, y = 1 - ecdf(count)(count))) +
  geom_point() +
  scale_x_continuous(trans = "log10", breaks = 10^(0:10))+
  scale_y_continuous(trans = "log10", breaks = 10^(0:-10)) 

これだけでよい。ラクチン!

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?