带叠加层的ggplot - 使用其他标签命名叠加层

时间:2017-05-31 09:11:50

标签: r ggplot2

我在y轴上有一个带有标签的图,用于区域图中的组。我添加了一个叠加层并想要命名这些。

底部的可重复数据。对于上下文,我正在显示网站会话数据,并希望在电视广告系列投放时进行重叠。

这是我的ggplot以及它的样子。下面是生成我正在使用的随机数据的命令。

timeline <- ggplot(dataset, aes(x = Month, y = Sessions,fill = Channel, group = Channel)) +
  geom_area(alpha = 0.2) +
  stat_summary(aes(group = 2), fun.y = sum, geom = 'line', size = 2, alpha = 0.5) +
  theme(axis.text.x=element_text(angle=90, hjust=1),
        axis.title.x = element_blank()) +
  geom_rect(data = tv_overlay, inherit.aes = FALSE,
            aes(xmin = start, xmax = end,
                ymin = -Inf, ymax = Inf),
            fill = "black", alpha = 0.1)

这会产生以下图表。请注意矩形叠加层,用于表示电视广告系列。如何为这些添加标签说“电视广告系列”: enter image description here

可重复的数据,允许上述命令用于时间线&lt; - 运行

# dimensions
channels <- c("Facebook", "Youtube", "SEM", "Organic", "Direct", "Email")
last_month <- Sys.Date() %m+% months(-1) %>% floor_date("month")
mts <- seq(from = last_month %m+% months(-23), to = last_month, by = "1 month")
yr_month <- format(mts, "%b-%Y")
dimvars <- expand.grid(Month = yr_month, Channel = channels)

# metrics
rws <- nrow(dimvars)
set.seed(42)

# generates variablility in the random data
randwalk <- function(initial_val, ...){
  initial_val + cumsum(rnorm(...))
}

Sessions <- ceiling(randwalk(3000, n = rws, mean = 8, sd = 1500)) %>% abs()
Transactions <- ceiling(randwalk(200, n = rws, mean = 0, sd = 75)) %>% abs()
Revenue <- ceiling(randwalk(10000, n = rws, mean = 0, sd = 3500)) %>% abs()

# make primary df
dataset <- cbind(dimvars, Sessions, Transactions, Revenue)

# make TV and Mass df for overlays
tv_begin <- sample(mts, 4)
tv_end <- tv_begin %m+% months(1)
tv_overlay <- data.frame(start = format(tv_begin, "%b-%Y"), end = format(tv_end, "%b-%Y"))

1 个答案:

答案 0 :(得分:0)

alpha映射到字符值以获取额外的图例条目:

ggplot(dataset, aes(x = Month, y = Sessions,fill = Channel, group = Channel)) +
  geom_area(alpha = 0.2) +
  stat_summary(aes(group = 2), fun.y = sum, geom = 'line', size = 2, alpha = 0.5) +
  geom_rect(aes(xmin = start, xmax = end, ymin = -Inf, ymax = Inf, alpha = "TV Campaign"),
            tv_overlay, inherit.aes = FALSE, fill = "black") +
  scale_alpha_manual(name = '', values = c("TV Campaign" = 0.1)) +
  theme(axis.text.x=element_text(angle=90, hjust=1),
        axis.title.x = element_blank())

enter image description here