2017-04-25 2 views
0

次のデータセットのヒストグラムをプロットしようとしています。このgistogramsは、このグループ内の総出生のための母親の年齢とそれぞれのカウントのための一意の各グループの棒を持っている必要があります。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 

私はggplotを使用してヒストグラムをプロットしようとしています:

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

をあなたは要約機能としてsumstat = 'summary'geom_barを使用することができますD ataはすでにbinnedされているので、 '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は明らかな解決策ではありません。あなたの前にちょうど集計プロット

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

関連する問題