ggplot2 axis limit gotchas

(This article was first published on Silent Spring Institute Developer Blog, and kindly contributed to R-bloggers)

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:


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

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. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.


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)