Search code examples
rggplot2limitfillgeom-area

Fill area between axis and plot fill area (ggplot2)


I am using this code:

 library(tidyverse)
 set.seed(143)
 series <- data.frame(
   time = c(rep(2017, 4),rep(2018, 4), rep(2019, 4), rep(2020, 4)),
   type = rep(c('a', 'b', 'c', 'd'), 4),
   value = rpois(16, 10)
   )
 plot1 <- ggplot(series, aes(time, value)) +
   geom_area(aes(fill = type))
 plot2 <- ggplot(series, aes(time, value)) +
   geom_area(aes(fill = type)) +
   scale_x_continuous(limits=c(2018, 2020), breaks=seq(2014, 2021, by=1))

For plot2, how can I expand the 'fill' between x=2018 and the y-axis? I would not like to see 2017 itself (as in plot1), but I would like to see this 'fill' between the y-axis (say x=2017.8) and x=2018.

I tried limits=c(2017.8, 2020), but no luck.

Edit

This is what I am looking for: enter image description here


Solution

  • ggplot(series, aes(time, value)) +
      geom_area(aes(fill = type)) + 
      coord_cartesian(xlim=c(2017.8, 2020)) +
      scale_x_continuous(breaks=seq(2018, 2021, 1))
    

    Gives

    enter image description here

    coord_cartesian() includes all input data in calculations (smoothing, interpolation etc), produces the plot and then crops the resulting image as requested. In contrast, lims(), xlim() and ylim() etc set points outside the requested limits to NA before performing calculations and constructing the plot.