Density Plot Not Displaying Proper Densities

Viewed 241

My data & code

library(ggplot2)
Year <- c(rep(1997, 8), rep(2004, 6), rep(2005, 3), rep(2006, 5),
          rep(2007, 7), rep(2008, 2), rep(2009, 8), rep(2010, 12),
          rep(2011, 18), rep(2012, 7), rep(2013, 6), rep(2014, 9),
          rep(2015, 7), rep(2016, 5), rep(2017, 3), rep(2018, 18),
          rep(2019, 40))

Group <- c(rep("b", 6), rep("c", 2), rep("b", 2), rep("c", 1), rep("d", 3), 
           rep("d", 3), rep("d", 5), rep("c", 1), rep("d", 6), rep("b", 2), 
           rep("a", 3), rep("b", 2), rep("c", 1), rep("d", 2), rep("b", 8),
           rep("c", 4), rep("b", 1), rep("c", 6), rep("d", 11),rep("a", 1),
           rep("b", 4), rep("c", 2), rep("a", 1), rep("c", 1), rep("d", 4), 
           rep("b", 5), rep("c", 4), rep("b", 2), rep("c", 5), rep("b", 1), 
           rep("c", 3), rep("d", 1), rep("a", 2), rep("d", 1), rep("a", 3), 
           rep("b", 7), rep("c", 7), rep("d", 1), rep("a", 13), rep("d", 27))

data <- data.frame(Year, Group)

table(data$Year, data$Group)

Doing tables on this would suggest that there's a huge bump in group D in 2019. By the end, Group D has 39% of observations and A has 14% (2018 it was 29% and 8%).

table(data$Year, data$Group) 
        a  b  c  d
  1997  0  6  2  0
  2004  0  2  1  3
  2005  0  0  0  3
  2006  0  0  0  5
  2007  0  0  1  6
  2008  0  2  0  0
  2009  3  2  1  2
  2010  0  8  4  0
  2011  0  1  6 11
  2012  1  4  2  0
  2013  1  0  1  4
  2014  0  5  4  0
  2015  0  2  5  0
  2016  0  1  3  1
  2017  2  0  0  1
  2018  3  7  7  1
  2019 13  0  0 27

But, when I do geom_density in ggplot2:

ggplot(data, aes(x=Year)) + 
  stat_density(geom="line", aes(group=Group, linetype=Group, color=Group))+
  ylab("Density")+
  scale_colour_manual(values = c("brown","gold", "green", "red"))+
  scale_linetype_manual(values = c("twodash", "solid", "dotted", "longdash")) +
  theme_bw()+
  theme(panel.grid.major=element_blank(),
        panel.grid.minor=element_blank(),
        panel.border=element_blank(),
        axis.line=element_line(),
        text=element_text(family='Times'),
        legend.title=element_blank())

Group A has this huge bump. I've checked the levels; I've tried it with lattice::densityplot(), etc. Am I not understanding how geom_density displays things?

Edit: Adding a photo of the graph that gets outputted for clarity. graph shows group a with big increase instead of d

0 Answers
Related