如何在ggplot2中制作累积图层图

时间:2018-08-08 14:04:46

标签: r ggplot2

我有一个类似于以下示例的数据:

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

现在,我需要用每天的距离总和来构建一个图,其中后续层将引用不同的载体。我的意思类似于

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

但将sum作为stat

我尝试过

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')

但它没有成功,导致

  

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

使用geom_bar很容易,但是有什么想法可以制作堆积的geom_area情节吗?

1 个答案:

答案 0 :(得分: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')

应该可以解决问题。 enter image description here