Search code examples
rggplot2

Use xlim(,) and scale_x_reverse() together in ggplot2


I am trying to use xlim and scale_x_reverse together in a plot, e.g.:

p <- ggplot(mtcars, aes(x = wt, y=mpg), . ~ cyl) + geom_point()
p + geom_line() +
  xlim(2, 5) +
  scale_x_reverse() 

Both commands work independently, but not together.Instead I get:

Scale for 'x' is already present. Adding another scale for 'x', which will replace the existing scale.

Is there a way to get work at the same time?

Thanks,

Mace


Solution

  • p + geom_line() +
      scale_x_reverse(limits = c(5, 2)) 
    #Warning messages:
    #1: Removed 7 rows containing missing values (geom_point). 
    #2: Removed 7 rows containing missing values (geom_path).
    

    first resulting plot

    p + geom_line() +
      scale_x_reverse() +
      coord_cartesian(xlim = c(5, 2))
    

    second resulting plot