2017-01-26 19 views
0

Population pyramid plot with ggplot2 and dplyr (instead of plyr)と同様に、Rに年代ピラミッドをプロットしたいと思います。Rの年齢ピラミッド(グループデータを使用)

問題は、私のデータがすでにサブグループによって集約されていることです。だから私は、65歳の発生数が、年齢であるすべての数字の合計をカウントしたくない65

例えば:私はこのコードを変更する必要がありますどのように

df = structure(list(number = c(26778, 28388, 23491, 18602, 15787, 
24536), gender = c("F", "M", "F", "M", "F", "M"), age = c(65, 
65, 65, 65, 74, 58)), .Names = c("number", "gender", "age"), row.names = c(142L, 
234L, 243L, 252L, 298L, 356L), class = "data.frame") 

library("ggplot2") 
ggplot(data = df, aes(x = age, fill = gender)) + 
    geom_bar(data = subset(df, gender == "M")) + 
    geom_bar(data = subset(df, gender == "F"), 
      mapping = aes(y = - ..count..), 
      position = "identity") + 
    scale_y_continuous(labels = abs) + 
    coord_flip() 

答えて

2

あなたは、事前にデータを要約して、以下のようにggplotにそれを渡すことができます。

df1 <- df %>% group_by(gender,age) %>% summarise(s_age = sum(age)) 

ggplot(data = df1, aes(x = age,y=s_age, fill = gender)) + 
    geom_bar(data = filter(df1, gender == "F"), stat = "identity") + 
    geom_bar(data = filter(df1, gender == "M"), stat="identity", aes(y=-s_age)) + 
    coord_flip() 

enter image description here