简体   繁体   中英

Add different overlay names to chart using e.g. alpha or scale_alpha_manual

I have a plot and have added two geom_rect overlays to it. The plot is a timeline and the two overlays are supposed to signify events that took place to provide context of the timeline.

My data look like this:

> glimpse(pdata_world)
Observations: 108
Variables: 2
$ date             <date> 2019-04-01, 2019-04-02, 2019-04-03, 2019-04-04, 2019-04-05, 2019-04-06, 2019-04-07, 2019-04-08, 2019-04-09…
$ organic_installs <dbl> 1572, 1593, 2391, 2857, 2015, 2677, 3800, 3308, 855, 2122, 4420, 2979, 4324, 4532, 3775, 3490, 3487, 3605, …
> glimpse(usa_launch_overlay)
Observations: 1
Variables: 2
$ start <date> 2019-05-28
$ end   <date> 2019-05-30
> glimpse(marketing_campaign_overlay)
Observations: 1
Variables: 2
$ start <date> 2019-06-24
$ end   <date> 2019-07-17

And here's my plot:

pdata_world %>%
  ggplot(aes(x = date, y = organic_installs)) +
  geom_line() +
  geom_rect(data = marketing_campaign_overlay, inherit.aes = F,
            aes(xmin = start, xmax = end,
                ymin = -Inf, ymax = Inf,
                alpha = "Marketing Campaign"),
            fill = "black") +
  geom_rect(data = usa_launch_overlay, inherit.aes = F,
            aes(xmin = start, xmax = end,
                ymin = -Inf, ymax = Inf,
                alpha = "USA Launch"),
            fill = "blue") +
    scale_alpha_manual(name = '', values = c("USA Launch" = 0.1, "Marketing Campaign" = 0.1))

I'm very close to what I want here, except that the color of both legends are blue so it's hard to distinguish which is which: 在此处输入图片说明

Both 'Marketing Campaign" and "USA Launch" overlays are blue on the legend. How can I control them to make the USA launch square in the legend blue like in the chart and the marketing campaign overlay black like in the chart?

I would not use the alpha scale that way. In fact, you should be getting a warning message about it.

I would instead use the fill scale and set alpha to a suitable level outside the aesthetic mapping. Something more like this:

pdata_world %>%
  ggplot(aes(x = date, y = organic_installs)) +
  geom_line() +
  geom_rect(data = marketing_campaign_overlay, inherit.aes = F,
            aes(xmin = start, xmax = end,
                ymin = -Inf, ymax = Inf,
                fill = "Marketing Campaign"),
            alpha = 0.1) +
  geom_rect(data = usa_launch_overlay, inherit.aes = F,
            aes(xmin = start, xmax = end,
                ymin = -Inf, ymax = Inf,
                fill = "USA Launch"),
            alpha = 0.1) +
    scale_fill_manual(name = element_blank(), values = c("USA Launch" = "yellow", "Marketing Campaign" = "purple"))

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