ylim in coord_cartesian by facet

931 views
Skip to first unread message

Tyler Hoecker

unread,
Dec 7, 2016, 7:29:40 PM12/7/16
to ggplot2
Hi everybody,

I am trying to manipulate the coord_cartesian ylim parameter as a function of each facet's data. Specifically, I would like to scale the limits on the y axis to the 90th percentile of the data, so that variability in small numbers can be seen. When different facets have widely varying scales, there is no way to adjust the limits individually. 
For example:

ggplot(mtcars, aes(x=mpg, y=hp)) +
  geom_point() +
  coord_cartesian(ylim = c(0, quantile(hp, 0.90)))+
  facet_grid(cyl ~.) 

> Error in quantile(hp, 0.9) : object 'hp' not found

Why doesn't coord_cartesian inherit the data and facet? If I specify mtcars$hp, then I would get the 90th percentile of all cylinder classes, but I want the limits to be scaled to the 90th percentile of each cylinder class individually. Any ideas?

Thanks!
Tyler

Hefin Rhys

unread,
Dec 9, 2016, 10:47:23 AM12/9/16
to ggplot2
I'm not entirely sure why, but if you specify the dataframe containing hp, it seems to work:


ggplot(mtcars, aes(x=mpg, y=hp)) +
  geom_point() +
  coord_cartesian(ylim = c(0, quantile(mtcars$hp, 0.90)))+
  facet_grid(cyl ~.)

Hefin

Hefin Rhys

unread,
Dec 9, 2016, 11:13:05 AM12/9/16
to ggplot2
Sorry, I misunderstood. There may be a more succinct way to do this, but the way I like to specify the axes is by including a dummy dataframe in a blank geom as below. The alternative is to simply let the scales be "free" and allow ggplot to scale the axes to your data as in  "facet_grid(cyl ~., scales = "free_y")".

cyl4 <- quantile(mtcars$hp[mtcars$cyl == 4], 0.9)
cyl6 <- quantile(mtcars$hp[mtcars$cyl == 6], 0.9)
cyl8 <- quantile(mtcars$hp[mtcars$cyl == 8], 0.9)

dummy <- data.frame(hp = c(0, cyl4, 0, cyl6, 0, cyl8), cyl = c(4, 6, 8),
                    mpg = rep(0, 6))


ggplot(mtcars, aes(x=mpg, y=hp)) +
  geom_point() +
  facet_grid(cyl ~., scales = "free_y") +
  geom_blank(data = dummy)

Hefin Rhys

unread,
Dec 9, 2016, 11:41:28 AM12/9/16
to ggplot2

Again, sorry it is NOT my day, correction to the dummy dataframe below:


cyl4 <- quantile(mtcars$hp[mtcars$cyl == 4], 0.9)
cyl6 <- quantile(mtcars$hp[mtcars$cyl == 6], 0.9)
cyl8 <- quantile(mtcars$hp[mtcars$cyl == 8], 0.9)

dummy <- data.frame(hp = c(0, cyl4, 0, cyl6, 0, cyl8), cyl = c(4, 4, 6, 6, 8, 8),

Tyler Hoecker

unread,
Dec 9, 2016, 11:41:33 AM12/9/16
to ggplot2
Hefin, 
That's a clever solution. I have not used geom_blank before. I will give that a shot with my real data; I ended up just functionalizing the plotting command, building them separately, and putting them together with grid.arrange.
Thanks!
Tyler
Reply all
Reply to author
Forward
0 new messages