2017-06-19 54 views
1

我想對部分數據進行直方圖放大。我的問題是,我想剔除範圍之外的所有內容,並將其歸入最後一類「10+」。使用ggplot2可以做到嗎?使用ggplot2在直方圖中對數據進行極限分組

示例代碼:

x <- data.frame(runif(10000, 0, 15)) 
ggplot(x, aes(runif.10000..0..15.)) + 
    geom_histogram(aes(y = (..count..)/sum(..count..)), colour = "grey50", binwidth = 1) + 
    scale_y_continuous(labels = percent) + 
    coord_cartesian(xlim=c(0, 10)) + 
    scale_x_continuous(breaks = 0:10) 

這裏是直方圖現在的樣子: How the histogram looks now

這裏是我怎麼想它看起來: How the histogram should look

也許這是不可能性,以通過嵌套ifelses來做到這一點,但正如我在我的問題中,更多的情況下ggplot可以做到這一點嗎?

+2

通常的策略與ggplot2是要更改數據,如果你想要這種類型的變化。因此,例如,您可以創建一個具有「10+」類別的變量,其中此bin中的所有值都在此處。然後繪圖很簡單。 (還有,「搶答」?你的意思是「分組」?) – RobertMc

+0

哦!抱歉我的拼寫錯誤! –

+0

沒問題!我只是想確保它不是別的:-) – RobertMc

回答

1

您可以使用forcatsdplyr對這些值進行有效分類,合計最後的「水平」,然後計算繪圖前的百分比。像這樣的東西應該工作:

library(forcats) 
library(dplyr) 
library(ggplot2) 

x <- data.frame(x = runif(10000, 0, 15)) 
x2 <- x %>% 
    mutate(x_grp = cut(x, breaks = c(seq(0,15,1)))) %>% 
    mutate(x_grp = fct_collapse(x_grp, other = levels(x_grp)[10:15])) %>% 
    group_by(x_grp) %>% 
    dplyr::summarize(count = n()) 

ggplot(x2, aes(x = x_grp, y = count/10000)) + 
    geom_bar(stat = "identity", colour = "grey50") + 
    scale_y_continuous(labels = percent) 

但是,得到的圖是從你的榜樣有很大不同,但我認爲這是正確的,因爲我們正在建設一個均勻分佈:

enter image description here