2017-10-13 142 views
0

以下代碼將創建一個直方圖並將計數標籤放在每個小節中。在stat_bin中使用自定義標籤ggplot

breaks=seq(0,100,by=10) 
ggplot(df, aes(x=spread,y=..count../sum(..count..))) + 
    stat_bin(breaks=breaks,fill='red',colour='black')+ 
stat_bin(breaks=breaks,geom='text',aes(label=..count..),vjust=-1.5,pad=FALSE)+ 
    scale_x_continuous(breaks=breaks) 

有10個箱,我希望把我自己的(不算)標籤在各條 ,例如

my_label=log(1:10) #Could be anything here 
ggplot(df, aes(x=spread,y=..count../sum(..count..))) + 
    stat_bin(breaks=breaks,fill='red',colour='black')+ 
    stat_bin(breaks=breaks,geom='text',aes(label=my_label),vjust=-1.5,pad=FALSE)+ 
    scale_x_continuous(breaks=breaks) 

如果我這樣做,這樣我得到一個錯誤: Error: Aesthetics must be either length 1 or the same as the data (847): label, x

有沒有一種簡單的方法來做到這一點?我知道有些人建議使用dplyr軟件包並修改數據幀(df),從而基本上創建原始數據幀的統計數據幀。有什麼比這更簡單嗎?畢竟,我們使用直方圖繪圖來避免自己執行分箱和統計。

+0

你有沒有看'?geom_histogram' –

+0

CON你提供一些樣本數據,例如使用'dput(df)' – Jimbou

回答

0
library(ggplot2) 
set.seed(1) 
breaks <- seq(0,100,by=10) 
df <- data.frame(spread = rnorm(1000,50,10)) 
my_label <- letters[1:10] #Could be anything here 
ggplot(df, aes(x=spread,y=..count../sum(..count..))) + 
    stat_bin(breaks=breaks,fill='red',colour='black')+ 
    stat_bin(breaks=breaks,geom='text',label=my_label,vjust=-1.5,pad=FALSE)+ 
    scale_x_continuous(breaks=breaks) 

enter image description here

編輯
這裏是另一個問題,一個解決方案要求通過@ user5768239:
有沒有辦法去除的標籤,其中..count .. == 0?

breaks <- seq(0,100,by=10) 
set.seed(123) 
df <- data.frame(spread = rnorm(1000,40,8)) 
spread_cat <- cut(df$spread, breaks=breaks) 
tbl <- table(spread_cat) 
my_label <- letters[1:10] #Could be anything here 
my_label[tbl==0] <- "" 
ggplot(df, aes(x=spread,y=..count../sum(..count..))) + 
    stat_bin(breaks=breaks,fill='red',colour='black')+ 
    stat_bin(breaks=breaks,geom='text',label=my_label,vjust=-1.5,pad=FALSE)+ 
    scale_x_continuous(breaks=breaks) 

enter image description here

+0

這工作,謝謝! – user5768239

+0

有沒有辦法刪除標籤'a'和'j'..count .. == 0?它看起來並不像我們可以使用..count ..在aes()之外。 – user5768239

+0

謝謝。如果我不提前知道哪些標籤有..count .. == 0並且想要刪除這些標籤? – user5768239