3

I've got a data similar to example below:

library(dplyr)
nycflights13::flights %>% 
  mutate(date = as.Date(paste(day, month, year, sep = '-'), format = '%d-%m-%Y')) %>% 
  select(date, carrier, distance)

Now I need to build a plot with stacked sums of distance in each day, where subsequent layers would refer to different carriers. I mean something similar to

ggplot(diamonds, aes(x = price, fill = cut)) + geom_area(stat = "bin") 

but with sum as a stat.

I have tried with

nycflights13::flights %>% 
  mutate(date = as.Date(paste(day, month, year, sep = '-'), format = '%d-%m-%Y')) %>% 
  select(date, carrier, distance) %>% 
  ggplot() + 
  geom_area(aes(date, distance, fill = carrier, group = carrier), stat = 'sum')

but it didn't do a trick, resulting in

Error in f(...) : Aesthetics can not vary with a ribbon

It's pretty easy with geom_bar, but any ideas how to make a stacked geom_area plot?

1 Answer 1

3
library(dplyr)
nycflights13::flights %>% 
  mutate(date = as.Date(paste(day, month, year, sep = '-'), 
                        format = '%d-%m-%Y')) %>% 
  select(date, carrier, distance) %>% 
  group_by(date, carrier) %>% 
  summarise(distance = sum(distance)) %>% 
  ggplot() + 
  geom_area(aes(date, distance, fill = carrier, 
                group = carrier), stat = 'identity')

should do the trick. enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

That's nice. I would from my personal experience avoid direct piping into the ggplot call. Assign your changed data frame to a new object. This makes it easier later to use several data frames for several plots, which you will most certainly have.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.