Skip to content
 

Make Andrew happy with one simple ggplot trick

By default, ggplot expands the space above and below the x-axis (and to the left and right of the y-axis). Andrew has made it pretty clear that he thinks the x axis should be drawn at y = 0. To remove the extra space around the axes when you have continuous (not discrete or log scale) axes, add the following to a ggplot plot,

plot <-
  plot + 
  scale_x_continuous(expand = c(0, 0)) + 
  scale_y_continuous(expand = c(0, 0))

Maybe it could even go in a theme.

Hats off to A5C1D2H2I1M1N2O1R2T1 (I can't make these handles up) for posting the solution on Stack Overflow.

15 Comments

  1. Josefina says:

    You can also do that with

    coord_cartesian(expand=F)

    Cheers!

  2. Ben Hanowell says:

    Dude… you just changed my life.

  3. Witold says:

    That’s handy. Thanks Bob!

  4. Jon Spring says:

    Or
    + expand_limits(y=0)

  5. Anoneuoid says:

    Hats off to A5C1D2H2I1M1N2O1R2T1 (I can’t make these handles up)

    Reminds me of clinical trial acroynyms.

    CITRUS-ALI, VITAMINS, ORANGES, HYVCTTSSS

  6. jd says:

    Nice! Thanks for posting this

  7. Andrew says:

    The moral of the story is: Do something that makes me happy, and it will make lots of other people happy too!

  8. This is one I don’t generally agree with. Too many times I have functions that are supposed to do things like asymptote to zero, and I want to see it actually go horizontal, not intersect the bottom of the frame and I have no idea what it did after that (does it go along the bottom of the frame, or is it crossing down below zero because of a bug?)

    Maybe this reflects the kinds of things I deal with rather than a general principle.

  9. Julien says:

    The problem is that this will also remove the space on the top.

    A better solution to only remove the space at the bottom is:

    + scale_y_continuous(expand=expand_scale(mult=c(0,.05)))

    or

    + scale_y_continuous(expand=expand_scale(add=c(0,10)))

    The first will add 5% only on the top, the second will add 10 units (also only at the top).

  10. F. George Dunham, III says:

    What about space at the top? Also, y=0 is just as limiting, should all be more open.

    Gary Stone has written in his blog that all coordinates should be considered to be absolute values. Of course, I think Gary Stone is a rabid fleash-eating hobbit so why would I listen to him? Ha aha aha ha! People don’t realize that Gary Stone learned UI dev from Rick “I’m a giant donkey” Thorn, so that’s why you shouldn’t read his blog. (Is that enough bait to finally get Gary to comment here????)

    Julien, best to approach it with % than units based on varying screen requirements.

Leave a Reply