2013-07-05 117 views
5

如何繪製R中ggplot2中的「step」或「staircase」直方圖?類似:如何在R中繪製ggplot2中的步驟直方圖?

enter image description here

其中每個水平線的寬度代表塊大小(x軸的值的)和高度對應於分數,在該倉落在數據的(不像附圖像,它是一個概率密度!)。有沒有辦法做到這一點geom_histogram

回答

8

產生一些數據:

foo <- data.frame(bar=rnorm(100)) 

直方圖步驟的geom和y軸計數:

ggplot(foo,aes(x=bar)) + stat_bin(geom="step") 

直方圖與步驟的geom和密度上y軸:

ggplot(foo,aes(x=bar)) + stat_bin(aes(y=..density..),geom="step") 

,並以「落入該倉數據的分數」:

ggplot(foo,aes(x=bar)) + stat_bin(aes(y=..count../sum(..count..)),geom="step") 

enter image description here

2

可能是其他更漂亮的方法來做到這一點,但這裏有一個想法。

foo <- data.frame(bar = rnorm(100)) + theme_bw() 
p <- ggplot(data = foo, aes(x = bar, y = ..count../sum(..count..))) ## or aes(x = bar, y = ..density..) if you want that 
p + geom_histogram(size = 2, colour = "red", fill = "white") + geom_histogram(colour = "transparent", fill = "white") 

enter image description here

編輯:

geom_histogram(size = 2, colour = "red", fill = "white")創建此 enter image description here

我編輯的輪廓的厚度size = 2做最後的輸出好看。在這個階段看起來很糟糕。要刪除您添加geom_histogram(colour = "transparent", fill = "white")將借鑑頂部的另一個直方圖覆蓋內部線(和一些這就是爲什麼我認爲size = 2看起來不錯的輪廓)的內線

+0

你能解釋一下爲什麼有兩個調用'geom_histogram'? – user248237dfsf

+0

@ user248237dfsf只需刪除第二個,看看會發生什麼。這應該是顯而易見的。 – Roland

+0

@Roland:我發現嘗試獲得正確的顏色/步驟形狀是個訣竅......但我不明白如何將這種情況推廣到'colour'被設置爲df中的變量以編碼不同條件的情況。 – user248237dfsf