简体   繁体   中英

How to set just one limit for axes in ggplot2 with facets?

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 (eg 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 as xlim(-5000, 5000) ) - it removes points entirely from consideration (eg 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.

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, eg 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))

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM