2017-04-25 52 views
0

我想繪製以下數據集的直方圖。這gistograms應該爲每個獨特的組在該組中總生育條對母親的年齡和相應的罪名:我想用ggplot繪製直方圖ggplot審美aes()返回錯誤stat_bin()

mother_age birth_count 
25 - 29    2 
30 - 34    1 
35 - 39    2 
40 - 44    2 
20 - 24    2 
25 - 29    7 
30 - 34    13 
35 - 39    5 
40 - 44    1 
15 - 19    5 
20 - 24    8 
25 - 29    25 
30 - 34    46 
35 - 39    31 
40 - 44    6 
15 - 19    16 
20 - 24    48 
25 - 29    162 
30 - 34    212 
35 - 39    100 
40 - 44    22 
15 - 19    7 
20 - 24    63 
25 - 29    162 
30 - 34    237 
35 - 39    128 
40 - 44    20 
15 - 19    1 
20 - 24    15 
25 - 29    48 

df1$mother_age <- as.factor(df1$mother_age) 
df1$birth_count <- as.numeric(df1$birth_count) 

mthr_chld <- ggplot(df1, aes(x=mother_age, y=birth_count)) + 
    ggtitle ("Mother Children") + 
    geom_histogram() + 
    labs(x = 'Mother\'s Age Group', y = 'Total Births') 

mthr_chld 

它拋出一個錯誤:

Error: stat_bin() must not be used with a y aesthetic. 

我在哪裏犯錯?

+0

d ata已經裝箱了,所以只需用'geom_bar'製作一個條形圖即可。你需要確保'mother_age_group'的因子級別也是有序的。 – alistaire

+1

'ggplot(df1,aes(mother_age,birth_count))+ geom_bar(stat ='identity')' – ahly

+0

@ahly非常感謝。讓我嘗試一下。 –

回答

1

您的數據已被分類,因此您不能使用geom_histogram但未彙總,因此geom_col不是明顯的解決方案。您可以使用stat = 'summary'geom_bar作爲sum彙總函數:

library(ggplot2) 

df <- read.table(text = 'mother_age_group birth_count 
         "25 - 29"    2 
         "30 - 34"    1 
         "35 - 39"    2 
         "40 - 44"    2 
         "20 - 24"    2 
         "25 - 29"    7 
         "30 - 34"    13 
         "35 - 39"    5 
         "40 - 44"    1 
         "15 - 19"    5 
         "20 - 24"    8 
         "25 - 29"    25 
         "30 - 34"    46 
         "35 - 39"    31 
         "40 - 44"    6 
         "15 - 19"    16 
         "20 - 24"    48 
         "25 - 29"    162 
         "30 - 34"    212 
         "35 - 39"    100 
         "40 - 44"    22 
         "15 - 19"    7 
         "20 - 24"    63 
         "25 - 29"    162 
         "30 - 34"    237 
         "35 - 39"    128 
         "40 - 44"    20 
         "15 - 19"    1 
         "20 - 24"    15 
         "25 - 29"    48', head = T) 

ggplot(df, aes(mother_age_group, birth_count)) + 
    geom_bar(stat = 'summary', fun.y = sum) 

...或只是聚集在你面前的情節:

library(dplyr) 

df %>% count(mother_age_group, wt = birth_count) %>% 
    ggplot(aes(mother_age_group, n)) + 
    geom_col() 

+0

完美,但正如@ahly所建議的那樣,'geom_bar(stat ='identity')'仍然是一小段代碼,並且與您所建議的完全相同。我想知道哪一個會更好用,爲什麼? –

+1

'geom_col'是'geom_bar(stat ='identity')'的快捷方式。兩者都直接在'df'上工作,但不是以一種非常明顯的方式:它實際上是爲每一行繪製一個條形圖,並將它們堆疊起來,因爲'position'的默認值是''stack''。所以是的,'ggplot(df,aes(mother_age_group,birth_count))+ geom_col()'起作用,只是稍微不直觀。 – alistaire