2010-08-23 154 views
27

我正在尋找一種更簡單的方法來繪製ggplot中的累積分配線。更容易的方法來繪製ggplot中的累積頻率分佈?

我有一些數據,其直方圖我可以馬上顯示與

qplot (mydata, binwidth=1); 

我找到了一種方法,在http://www.r-tutor.com/elementary-statistics/quantitative-data/cumulative-frequency-graph做到這一點,但它涉及幾個步驟和探索數據時,它的耗時。

有沒有辦法在ggplot中以更簡單的方式實現它,類似於通過指定選項可以添加趨勢線和置信區間?

回答

23

在R中有一個內置的ecdf()函數應該使事情變得更容易。下面是一些示例代碼,利用plyr

library(plyr) 
data(iris) 

## Ecdf over all species 
iris.all <- summarize(iris, Sepal.Length = unique(Sepal.Length), 
          ecdf = ecdf(Sepal.Length)(unique(Sepal.Length))) 

ggplot(iris.all, aes(Sepal.Length, ecdf)) + geom_step() 

#Ecdf within species 
iris.species <- ddply(iris, .(Species), summarize, 
          Sepal.Length = unique(Sepal.Length), 
          ecdf = ecdf(Sepal.Length)(unique(Sepal.Length))) 

ggplot(iris.species, aes(Sepal.Length, ecdf, color = Species)) + geom_step() 

編輯我只是意識到你想累積頻率。你可以得到由觀測總數ECDF值乘以:

iris.all <- summarize(iris, Sepal.Length = unique(Sepal.Length), 
          ecdf = ecdf(Sepal.Length)(unique(Sepal.Length)) * length(Sepal.Length)) 

iris.species <- ddply(iris, .(Species), summarize, 
          Sepal.Length = unique(Sepal.Length), 
          ecdf = ecdf(Sepal.Length)(unique(Sepal.Length))*length(Sepal.Length)) 
+0

這是一個很好的答案,但有一件事我無法弄清楚。在ecdf(Sepal.Length)(獨特的(Sepal.Length))中,發生了什麼?我明白它是從'ecdf'對象中提取具體的值,但我不記得在...之前看到過這個(x)(y)符號...你能幫我理解嗎?謝謝! – 2011-08-30 15:34:11

+3

@MattParker'ecdf()'返回一個函數,以便表示法以「Sepal.Length」的唯一值計算返回的函數。 – 2011-11-08 16:16:01

+0

@GavinSimpson明白了,謝謝! – 2011-11-08 16:31:46

20

即使簡單:

qplot(unique(mydata), ecdf(mydata)(unique(mydata))*length(mydata), geom='step') 
+0

酷,但如此簡潔,我很難轉換爲ggplot命令,我可以使用它來設置標題和軸標籤。 – dfrankow 2012-05-29 21:06:17

+0

我想我可以使用main,xlab,ylab。 – dfrankow 2012-05-29 21:06:42

+0

希望我可以upvote兩次,我不止一次回到這裏。 – dfrankow 2012-07-12 20:58:25

46

GGPLOT2的新版本(0.9.2.1)有一個內置stat_ecdf()功能讓您可以非常輕鬆地繪製累積分佈。從GGPLOT2文檔

qplot(rnorm(1000), stat = "ecdf", geom = "step") 

或者

df <- data.frame(x = c(rnorm(100, 0, 3), rnorm(100, 0, 10)), 
      g = gl(2, 100)) 
ggplot(df, aes(x, colour = g)) + stat_ecdf() 

代碼示例。