'unable to set xlim and ylim using min() and max() in ggplot

I am missing something crucial here and can't see it.

Why does min and max not work to set the axis limits?

mtcars %>%  
  select(mpg, cyl, disp, wt) %>% 
  filter(complete.cases(disp)) %>% 
  ggplot() +
  geom_point(aes(x=mpg, y=disp, colour=cyl), size=3) +
  xlim(min(mpg, na.rm=TRUE),max(mpg, na.rm=TRUE)) +
  ylim(min(disp, na.rm=TRUE),max(disp, na.rm=TRUE)) +
  scale_colour_gradient(low="red",high="green", name = "cyl")

This works:

    mtcars %>%  
      select(mpg, cyl, disp, wt) %>% 
      filter(complete.cases(disp)) %>% 
      ggplot() +
      geom_point(aes(x=mpg, y=disp, colour=cyl), size=3) +
#      xlim(min(mpg, na.rm=TRUE),max(mpg, na.rm=TRUE)) +
#      ylim(min(disp, na.rm=TRUE),max(disp, na.rm=TRUE)) +
      scale_colour_gradient(low="red",high="green", name = "cyl")


Solution 1:[1]

ggplot cannot access the column values in the way that dplyr can.

You need to add in the data:

mtcars %>%  
  select(mpg, cyl, disp, wt) %>% 
  filter(complete.cases(disp)) %>% 
  ggplot() +
  geom_point(aes(x=mpg, y=disp, colour=cyl), size=3) +
  xlim(min(mtcars$mpg, na.rm=TRUE),max(mtcars$mpg, na.rm=TRUE)) +
  ylim(min(mtcars$disp, na.rm=TRUE),max(mtcars$disp, na.rm=TRUE)) +
  scale_colour_gradient(low="red",high="green", name = "cyl")

Solution 2:[2]

You can't reference column names in ggplot objects except inside aes() and in a formula or vars() in a facet_* function. But the helper function expand_scale is there to help you expand the scales in a more controlled way.

For example:

# add 1 unit to the x-scale in each direction
scale_x_continuous(expand = expand_scale(add = 1))
# have the scale exactly fit the data, no padding
scale_x_continuous(expand = expand_scale(0, 0))
# extend the scale by 10% in each direction
scale_x_continuous(expand = expand_scale(mult = .1))

See ?scale_x_continuous and especially ?expand_scale for details. It's also possible to selectively pad just the top or just the bottom of each scale, there are examples in ?expand_scale.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joel Carlson
Solution 2