ggplot + dplyr没有正确堆叠数据或删除数据

时间:2017-05-20 15:56:12

标签: r ggplot2 dplyr geom-bar

我正在尝试堆叠条形图,由于某种原因我的条形图没有正确堆叠。 The stacks are out of order and the colors consolidated.我不确定如何解决问题

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

这导致这个图形被正确堆叠,但正如您所看到的那样,它已经抛出了大量数据。是否有一些我可以使用的功能仍然可以整合数据而不会像汇总那样丢弃数据?

1 个答案:

答案 0 :(得分: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起绑架事件。