'Trying to make a stacked bar plot but geom_col giving error
I have these data:
> dput(events.bypod)
structure(list(event.id = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L,
10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L,
23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L, 34L, 35L,
36L, 37L, 38L, 39L, 40L, 41L, 42L, 43L, 44L, 45L, 46L, 47L, 48L,
49L, 50L, 51L, 53L, 54L, 55L, 56L, 57L, 58L, 59L, 60L, 61L, 62L,
63L, 64L, 65L, 66L, 67L, 68L, 69L, 70L, 71L, 72L, 73L, 74L, 75L,
77L, 78L, 43L, 45L, 50L, 67L), year = c(1962L, 1976L, 1981L,
1981L, 1982L, 1987L, 1989L, 1990L, 1992L, 1992L, 1992L, 1994L,
1998L, 2003L, 2003L, 2003L, 2003L, 2004L, 2004L, 2004L, 2005L,
2005L, 2005L, 2005L, 2005L, 2005L, 2005L, 2005L, 2005L, 2005L,
2006L, 2006L, 2006L, 2006L, 2006L, 2006L, 2007L, 2007L, 2007L,
2008L, 2008L, 2008L, 2009L, 2009L, 2009L, 2010L, 2010L, 2010L,
2011L, 2011L, 2013L, 2013L, 2014L, 2014L, 2014L, 2014L, 2014L,
2015L, 2015L, 2015L, 2015L, 2015L, 2016L, 2016L, 2016L, 2016L,
2016L, 2016L, 2017L, 2018L, 2018L, 2018L, 2019L, 2020L, 2020L,
2020L, 2009L, 2009L, 2011L, 2016L), pod = c("L", "L", "L", "L",
"L", "L", "L", "K", "L", "L", "L", "L", "L", "J", "L", "L", "J",
"L", "L", "L", "J", "J", "J", "J", "J", "L", "L", "J", "L", "L",
"J", "J", "K", "L", "L", "J", "L", "L", "K", "L", "L", "L", "J",
"J", "J", "L", "L", "K", "J", "L", "K", "K", "J", "J", "L", "J",
"L", "K", "K", "L", "J", "J", "J", "L", "J", "J", "L", "L", "J",
"J", "J", "J", "L", "J", "J", "L", "K", "K", "K", "L")), row.names = c(NA,
-80L), class = "data.frame")
And I made a stacked bar plot using this:
ggplot(events.bypod, aes(year, fill = pod))+
geom_bar()+theme_bw()
However these values aren't correct for what I want - eg, I know K pod only has 11 total instances yet this graph shows it has 19. I read this might be because I'm using geom_bar
(which counts proportions iirc) instead of geom_col
(which does the actual counts?), but when I try to do geom_col
, I get this error:
Error: geom_col requires the following missing aesthetics: y
I tried specifying:
ggplot(events.bypod, aes(x=year, y=frequency(event.id), fill = pod))+
geom_col()+theme_bw()
But I get the same graph.
Any help in getting the counts to display properly on my bar plot is greatly appreciated!
Solution 1:[1]
An option would be to first count
before plotting -
library(dplyr)
library(ggplot2)
events.bypod %>%
dplyr::count(year, pod, name = 'count') %>%
ggplot(aes(year, count, fill = pod)) +
geom_col()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |