6

This question is similar to this one: How to set limits for axes in ggplot2 R plots?, with the difference that I want to limit one side only (e.g. plot only for x>0 instead of -5000 < x < 5000 ) and do it with facets.

Note, I'd like to know solutions for both of these simple cases:

  1. scale_x_continuous(limits = c(-5000, 5000)) ( the same asxlim(-5000, 5000)) - it removes points entirely from consideration (e.g. they will not be used for geom_smooth())

  2. coord_cartesian(xlim = c(-5000, 5000)) functions - it simply does not plot them (but still uses for geom_smooth())

This situation happens often when you use facet_wrap(~veg, scales = "free_x) and don't know what the upper x limit for each facet, but you know that they are always positive.

IVIM
  • 2,167
  • 1
  • 15
  • 41
  • You should include an example, presumably where different facets should end up with different max values (otherwise it's trivial). – user2554330 Apr 30 '20 at 19:29
  • 1
    just set limits = c(-5000, NA) . This works for both coord and scales function – tjebo Apr 30 '20 at 20:22
  • 1
    Does this answer your question? [set only lower bound of a limit for ggplot](https://stackoverflow.com/questions/11214012/set-only-lower-bound-of-a-limit-for-ggplot) – tjebo Apr 30 '20 at 20:22
  • Simplest answer here is already in the comments above: @Tjebo, you should post it. Works like a charm. – chemdork123 Apr 30 '20 at 20:58
  • @chemdork123 cheers. Answer added – tjebo Apr 30 '20 at 21:07

2 Answers2

6

Set limits one-sided with NA. Works both in coord_ and scale_ functions

I generally prefer coord_ because it does not remove data. For the example below you would additionally need to remove the margin at 0, e.g. with expand.

library(ggplot2)    

carrots <- data.frame(length = rnorm(500000, 10000, 10000))
cukes <- data.frame(length = rnorm(50000, 10000, 20000))
carrots$veg <- 'carrot'
cukes$veg <- 'cuke'
vegLengths <- rbind(carrots, cukes)

ggplot(vegLengths, aes(length, fill = veg)) +
  geom_density(alpha = 0.2) +
  scale_x_continuous(limits = c(0, NA))
#> Warning: Removed 94542 rows containing non-finite values (stat_density).


ggplot(vegLengths, aes(length, fill = veg)) +
  geom_density(alpha = 0.2) +
  coord_cartesian(xlim = c(0, NA))

Created on 2020-04-30 by the reprex package (v0.3.0)

remove the margin with expand. Also one sided possible. the right margin is set to the default mult expansion of 0.05 for continous axis.

ggplot(vegLengths, aes(length, fill = veg)) +
  geom_density(alpha = 0.2) +
  scale_x_continuous(expand = expansion(mult = c(0, 0.05))) +
  coord_cartesian(xlim = c(0, NA))

tjebo
  • 21,977
  • 7
  • 58
  • 94
1

You can try

scale_x_continuous(limits = c(0, max(x)))

This will set the lower limit to zero, and the upper limit to the maximum of your data. Is that what you're looking for?

RyanFrost
  • 1,400
  • 7
  • 17