Search code examples
rggplot2dplyrgeom-bar

ggplot + dplyr not stacking data correctly or removing data


I'm trying to a stacked bar graph, and for some reason my bars are not stacking correctly. The stacks are out of order and the colors consolidated. I'm not really sure how to fix the problem

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

This results in this a graph that is correctly stacked, but as you can see by comparing the two that it has thrown out a lot of the data. Is there some function I could use that will still consolidate the data without throwing out data like summarise seems to be?


Solution

  • I think the first piece of code works. Granted, you can simplify it:

    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

    But this seems to be a correct representation of the data, if I understand it correctly. Just to check ourselves, lets check 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
    

    As depicted in the plot, we have 7 armed assault deaths, 6 bombing/explosion, 3 barricade and 3 kidnappings.