Annotation destroys the free scales in ggplot facets

The following plot is fine but the problem starts after annotation.

pkgs <- c("ggplot2", "dplyr", "lubridate")
for (pkg in pkgs) suppressPackageStartupMessages(require(pkg, character.only = TRUE))

require(ggplot2)
require(dplyr)
require(lubridate)

data("economics", package = "ggplot2")

economics %>% 
  mutate(year = year(date),
         decade = cut_interval(year, length = 10, dig.lab = 6)) %>% 
  ggplot(aes(date, unemploy/pop)) +
  facet_grid(cols = vars(decade), scales = 'free') +
  scale_x_date(date_breaks = "5 years", date_labels = "%Y") +
  geom_line()

Created on 2021-02-06 by the reprex package (v0.3.0)

After annotation,

pkgs <- c("ggplot2", "dplyr", "lubridate")
for (pkg in pkgs) suppressPackageStartupMessages(require(pkg, character.only = TRUE))

require(ggplot2)
require(dplyr)
require(lubridate)

data("economics", package = "ggplot2")

economics %>% 
  mutate(year = year(date),
         decade = cut_interval(year, length = 10, dig.lab = 6)) %>% 
  ggplot(aes(date, unemploy/pop)) +
  facet_grid(cols = vars(decade), scales = 'free') +
  scale_x_date(date_breaks = "5 years", date_labels = "%Y") +
  geom_line() +
  annotate(geom = "segment", color = "maroon", linetype = "dashed",
           x = as.Date("1982-12-01"), xend = as.Date("1982-12-01"),
           y = 0, yend = Inf)

Created on 2021-02-06 by the reprex package (v0.3.0)

The free scales are completely destroyed. Is there any way out with this problem?

I would use geom_vline. Is the following close to what you want?

require(ggplot2)
#> Loading required package: ggplot2
require(dplyr)
#> Loading required package: dplyr
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
require(lubridate)
#> Loading required package: lubridate
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union

data("economics", package = "ggplot2")

economics %>% 
  mutate(year = year(date),
         decade = cut_interval(year, length = 10, dig.lab = 6)) %>% 
  ggplot(aes(date, unemploy/pop)) +
  facet_grid(cols = vars(decade), scales = 'free') +
  scale_x_date(date_breaks = "5 years", date_labels = "%Y") +
  geom_line() +
  geom_vline(xintercept = as.Date("1982-12-01"),color = "maroon", linetype = "dashed")

Created on 2021-02-06 by the reprex package (v0.3.0)

1 Like

Thank you, I overlooked this.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.