直接在ggplot2中创建比例geom_area图

时间:2017-08-01 13:03:21

标签: r ggplot2 data.table dplyr

我想创建一个比例geom_area图。我认为必须有可能直接在ggplot2中执行此操作,而不是事先计算总数和比例。 我创建了一个最小的工作示例,它显示了我现在所拥有的内容。

library(data.table)
library(dplyr)
library(zoo)
dt <- structure(list(Date = structure(c(2000, 2000, 2000, 2000, 2000, 
                                  2000.25, 2000.25, 2000.25, 2000.25, 2000.25, 2000.5, 2000.5, 
                                  2000.5, 2000.5, 2000.5, 2000.75, 2000.75, 2000.75, 2000.75, 2000.75, 
                                  2001, 2001, 2001, 2001, 2001, 2001.25, 2001.25, 2001.25, 2001.25, 
                                  2001.25, 2001.5, 2001.5, 2001.5, 2001.5, 2001.5, 2001.75, 2001.75, 
                                  2001.75, 2001.75, 2001.75, 2002, 2002, 2002, 2002, 2002, 2002.25, 
                                  2002.25, 2002.25, 2002.25, 2002.25, 2002.5, 2002.5, 2002.5, 2002.5, 
                                  2002.5, 2002.75, 2002.75, 2002.75, 2002.75, 2002.75), class = "yearqtr"), 
               Category = c(2L, NA, 1L, 4L, 3L, 2L, NA, 1L, 4L, 3L, 2L, 
                            NA, 1L, 4L, 3L, 2L, NA, 1L, 4L, 3L, 2L, NA, 1L, 4L, 3L, 2L, 
                            NA, 1L, 4L, 3L, 2L, 1L, 4L, NA, 3L, 2L, 1L, 4L, NA, 3L, 2L, 
                            1L, 4L, NA, 3L, 2L, 1L, 4L, NA, 3L, 2L, 1L, 4L, NA, 3L, 2L, 
                            1L, 4L, NA, 3L), Value = c(51, 15, 17, 3, 37, 50, 16, 17, 
                                                       3, 47, 49, 16, 17, 3, 37, 53, 16, 17, 2, 38, 57, 2, 16, 2, 
                                                       39, 58, 2, 16, 2, 39, 59, 17, 2, 2, 38, 59, 16, 3, 2, 37, 
                                                       58, 17, 3, 3, 35, 58, 17, 3, 3, 36, 56, 17, 3, 3, 36, 57, 
                                                       17, 3, 3, 37))
,.Names = c("Date", "Category", "Value")
, class = c("data.table", "data.frame"), row.names = c(NA, -60L))
data.table::melt(dt, id.vars = c("Date", "Category")
, measure.vars = c("Value")
)  %>%  ggplot(data = ., aes(x = Date, y = value, fill = as.factor(Category))) +
    geom_area(stat = "identity") +
    theme(legend.title=element_blank()) + 
    scale_x_yearqtr(format = "%Y-Q%q",n = 8, expand = c(0,0))

Resulting graphic 我想将所有内容扩展到0到1的空间,让它完全填满。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您只需将position = "fill"添加到geom_area()

data.table::melt(dt, id.vars = c("Date", "Category")
                 , measure.vars = c("Value")
)  %>%  ggplot(data = ., aes(x = Date, y = value, fill = as.factor(Category))) +
  geom_area(stat = "identity", position = "fill") +
  theme(legend.title=element_blank()) + 
  scale_x_yearqtr(format = "%Y-Q%q",n = 8, expand = c(0,0))

结果:

enter image description here