jakes
jakes

Reputation: 2085

Stacked geom_area with multiple row data

I would like to make a stacked area plot. My data looks like below:

data <- structure(list(value = c(3.84, 5.21, 51.16, 0, 7.58, 1.81, 6.74, 
28.27, 6.49, 5.9, 6.15, 0.08, 26.23, 23.76, 24.68, 19.97, 2.89, 
2.84, 4.05, 18.24, 46.83, 30.47, 29.17, 0, 0.15, 0.23, 29.18, 
24.24, 38.58, 21.82, 33.85, 27.23, 27.91, 30.03, 75.12, 5.25, 
6.02, 6.1, 8.62, 81.01, 23.97, 27.99, 19.64, 57.61, 22.22, 19.76, 
18.05, 36.94, 29.13, 20.75, 26.07), category = c("C", "C", "A", 
"B", "C", "C", "C", "A", "C", "C", "C", "A", "B", "B", "B", "B", 
"C", "C", "C", "B", "B", "B", "B", "C", "C", "C", "B", "B", "B", 
"B", "B", "B", "B", "B", "A", "B", "B", "B", "B", "A", "C", "C", 
"C", "A", "C", "C", "C", "A", "A", "C", "C"), date = structure(c(17041, 
17041, 17042, 17042, 17042, 17042, 17042, 17043, 17043, 17043, 
17043, 17044, 17044, 17044, 17044, 17044, 17044, 17044, 17044, 
17045, 17045, 17045, 17045, 17045, 17045, 17045, 17046, 17046, 
17046, 17046, 17047, 17047, 17047, 17047, 17048, 17048, 17048, 
17048, 17048, 17049, 17049, 17049, 17049, 17050, 17050, 17050, 
17050, 17051, 17051, 17051, 17051), class = "Date")), class = "data.frame", row.names = c(NA, 
-51L))

I have tried the following

data %>% ggplot() + geom_area(aes(date, value, fill = category), position = 'stack')

but this gives me: enter image description here

I have also tried adding stat = 'sum' but it doesn't work neither. What am I doing wrong?

Upvotes: 0

Views: 104

Answers (1)

MrFlick
MrFlick

Reputation: 206197

When you have messy data like this, it's best to do the data manipulation yourself outside of ggplot. In order to get an area plot, you need to collapse multiple observations per day into 1 value and include zeros for days where there are no observations. You can do this with

data %>% 
  mutate(category=factor(category)) %>% 
  group_by(date, category) %>% 
  summarize_all(sum) %>% 
  tidyr::complete(date, category, fill=list(value=0)) %>% 
  ggplot(aes(date, value, fill=category)) + 
    geom_area(position="stack")

enter image description here

Upvotes: 1

Related Questions