ggplot2: automatic y limits with user-supplied x-axis limits

Viewed 107

The "limits" option in scale_x_* functions is said to clip off the data with values outside of the specified range. However, if I restrict the x range, automatic limits for the y axis are computed with the full set of data.

library(ggplot2)
ggplot(economics, aes(date, psavert)) +
  scale_x_date(limits = c(as.Date("2000-01-01"), as.Date("2010-12-31"))) + 
  geom_line()

produces an awful range for the y axis. Can I tell ggplot to use only the data with x values inside the specified limits to calculate the default y-axis range? I know how to do it manually, but I would like to use the built-in automatism.

1 Answers

Interesting observation - I don't know whether there is an elegant way to tell ggplot to scale y-axis. Only idea I'd have is to filter data before plotting:

economics %>%
    filter((date >= as.Date("2000-01-01")) & (date <= as.Date("2010-12-31"))) %>%
    ggplot(aes(date, psavert)) +
        geom_line()
Related