2017-05-20 9 views
1

積み上げ棒グラフを作成しようとしていますが、何らかの理由でバーが正しく積み重なっていません。 The stacks are out of order and the colors consolidated.私はこれはこれで正しく積層されているグラフをもたらしていますが、それが持っている2を比較して見ることができるようにどのように問題を解決するにはggplot + dplyr正しくデータを積み重ねたりデータを取り除いたりしません

g12<-terror %>% 
group_by(attacktype1_txt,iyear,nkillter) %>% 
ggplot(aes(x=iyear,y=nkillter,fill=attacktype1_txt)) + 
geom_bar(stat='identity',position='stack') + xlab('Year of Attack') + 
ylab('Number of Deaths') 
g12=g12+ guides(fill=guide_legend(title="Attack Types")) 
g12 

or when I try and use the summarise function to make the bars stack correctly I get this oddity

g12<-terror %>% 
group_by(attacktype1_txt,iyear,nkillter) %>% summarise(number=n()) %>% 
ggplot(aes(x=iyear,y=nkillter,fill=attacktype1_txt)) + 
geom_bar(stat='identity',position='stack') + xlab('Year of Attack') + 
ylab('Number of Deaths') 
g12=g12+ guides(fill=guide_legend(title="Attack Types")) 
g12 

本当にわからないんだけど多くのデータを投げ捨てました。要約のようなデータを放棄せずにデータを統合するために使用できる関数はありますか?

+0

問題を再現するために、データを提供する必要があります。 – nathaneastwood

+0

これはデータセットです https://drive.google.com/file/d/0BzgRASyCPi42RDdKY25adVZoWFk/view?usp=sharing – BaconBoi

答えて

0

私はコードの最初の作品が動作すると思います。

ggplot(terror, aes(iyear, nkillter)) + 
geom_bar(aes(fill = attacktype1_txt), stat = "identity") + 
    xlab('Year of Attack') + ylab('Number of Deaths') + 
    guides(fill=guide_legend(title="Attack Types")) 

enter image description here

をしかし、これは、私はそれを正しく理解すれば、データの正確な表現であるように思わ:確かに、あなたはそれを簡素化することができます。ただ、自分自身をチェックするために、2015年をチェックすることができます:

プロットに示されるように
> (terror %>% select(iyear, attacktype1_txt, nkillter) %>% 
       arrange(attacktype1_txt, nkillter) %>% 
       filter(iyear==2015, nkillter > 0)) 
     iyear      attacktype1_txt nkillter 
    1 2015      Armed Assault  1 
    2 2015      Armed Assault  1 
    3 2015      Armed Assault  1 
    4 2015      Armed Assault  1 
    5 2015      Armed Assault  1 
    6 2015      Armed Assault  2 
    7 2015     Bombing/Explosion  1 
    8 2015     Bombing/Explosion  1 
    9 2015     Bombing/Explosion  1 
    10 2015     Bombing/Explosion  1 
    11 2015     Bombing/Explosion  2 
    12 2015 Hostage Taking (Barricade Incident)  1 
    13 2015 Hostage Taking (Barricade Incident)  2 
    14 2015   Hostage Taking (Kidnapping)  3 

は、我々は7武力攻撃による死亡、6爆撃/爆発、3バリケードと3人の誘拐を持っています。

+0

これは本当に奇妙です。全く同じコードがこのグラフ出力につながります http://i.imgur.com/wHUIhjR.png – BaconBoi

+0

hmm .. ggplotのどのバージョンを実行していますか? –

関連する問題