85

In the following example, how do I get the y-axis limits to scale according to the data in each panel?

mt <- ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + geom_point() 

Neither of these will do it:

mt + facet_grid(. ~ cyl, scales="free")
mt + facet_grid(. ~ cyl, scales="free_y")
hatmatrix
  • 42,883
  • 45
  • 137
  • 231
  • Anyone have any idea what the intended purpose is of the `scales` argument for `facet_grid`? – geotheory Sep 24 '18 at 13:41
  • @geotheory it's in the docs. The scales argument is for freeing the x, y, or both scales for each facetted plot. Your options are 'fixed' (default), 'free_x', 'free_y', or 'free' for both. Use it when the ranges of your variables vary greatly and need to be freed. – kentkr Apr 09 '21 at 21:26

5 Answers5

91

Perhaps it's because you have only one y axis, using your way. Did you try something like this?

mt + facet_grid(cyl ~ ., scales="free")
gd047
  • 29,749
  • 18
  • 107
  • 146
  • 2
    I see - so it doesn't scale each panel by by rows or columns... in the case facet_wrap() also works I guess. – hatmatrix Sep 10 '10 at 15:20
  • How about plotting the same data but usign barplots? I asked just that [here](http://stackoverflow.com/questions/29262916/how-i-get-a-facet-grid-plot-with-free-scales-and-barplots-with-ggplot2) – Juan Mar 25 '15 at 17:52
  • 12
    I feel this does not resolve the issue. I am having the same problem, and all "cyl ~ ." did was flip the axes. Now, the x axis is what I want to be free, but it is not free. I am using R version 3.2.3 with ggplot2 version 2.1.0. – landau Mar 26 '16 at 17:45
39

You can't. See here

You can use facet_wrap instead, which will 'free' both axes

jf328
  • 6,841
  • 10
  • 58
  • 82
37

I'm sorry for jumping on this 12 year old question with a new answer, but I think it might be useful. If you want to preserve the grid layout, but want wrap-like free scales, you might be interested in ggh4x::facet_grid2() which has an independent argument that lets an axis vary within a row or column in a grid-layout.

library(ggplot2)

ggplot(mtcars, aes(mpg, wt, colour = factor(cyl))) + 
  geom_point() +
  ggh4x::facet_grid2(. ~ cyl, scales = "free_y", independent = "y")

Created on 2022-06-09 by the reprex package (v2.0.1)

(Disclaimer: I'm the author of ggh4x)

teunbrand
  • 33,645
  • 4
  • 37
  • 63
21

Hopefully, this helps.

mt + facet_wrap(. ~ cyl, scales="free_y")
Craig Forbes
  • 231
  • 2
  • 3
1

Try: https://teunbrand.github.io/ggh4x/reference/facet_grid2.html.

This code allows to make the scales of each panel independent using facet_grid, but with facet_grid2.