Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

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")
like image 673
val Avatar asked Apr 16 '18 21:04

val


2 Answers

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")
like image 133
Joel Carlson Avatar answered Nov 15 '22 00:11

Joel Carlson


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.

like image 20
Gregor Thomas Avatar answered Nov 15 '22 00:11

Gregor Thomas