ggplot2 axis limit gotchas

[This article was first published on Silent Spring Institute Developer Blog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Setting axis limits in ggplot has behaviour that may be unexpected: any data that falls outside of the limits is ignored, instead of just being hidden. This means that if you are apply a statistic or calculation on the data, like plotting a box and whiskers plot, the result will only be based on the data within the limits.

In other words, ggplot doesn’t “zoom in” on a part of your plot when you apply an axis limit, it recalculates a new plot with the restricted data.

For example, here is a boxplot without any axis limits:

library(ggplot2)
data(iris)

ggplot(iris, aes(x = Species, y = Petal.Length)) +
  geom_boxplot()

plot of chunk unnamed-chunk-1

and here is the same one with a set Y axis limit:

ggplot(iris, aes(x = Species, y = Petal.Length)) +
  geom_boxplot() +
  ylim(c(1, 4))
## Warning: Removed 84 rows containing non-finite values (stat_boxplot).

plot of chunk unnamed-chunk-2

Note how the box and whiskers are recalculated in this plot. To be fair, ggplot does warn you that it is removing rows!

If you want to zoom in without removing values, use coord_cartesian:

ggplot(iris, aes(x = Species, y = Petal.Length)) +
  geom_boxplot() +
  coord_cartesian(ylim = c(1, 4))

plot of chunk unnamed-chunk-3

To leave a comment for the author, please follow the link and comment on their blog: Silent Spring Institute Developer Blog.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)