简体   繁体   中英

how to make a cumulative layer plot in ggplot2

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?

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. 在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM