6

I've got some data that share a common x-axis but have two different y variables:

set.seed(42)
data = data.frame(
    x = rep(2000:2004, 2),
    y = c(rnorm(5, 20, 5), rnorm(5, 150, 15)),
    var = rep(c("A", "B"), each = 5)
)

I'm using a faceted line plot to display the data:

p = ggplot(data, aes(x, y)) +
    geom_line() +
    facet_grid(var ~ ., scales = "free_y")

enter image description here

I'd like the y-axis to include 0. This is easy enough:

p + expand_limits(y = 0)

but then my data looks crowded too close to the top of my facets. So I'd like to pad the range of the axis. Normally scale_y_continuous(expand = ...) is used for padding the axis, but the padding is applied symmetrically to the top and bottom, making the y-axis go well below 0.

p + expand_limits(y = 0) + 
    scale_y_continuous(expand = c(0.3, 0.2))
# the order of expand_limits and scale_y_continuous
# does not change the output

enter image description here

I can't explicitly set limits because of the facets with free y scales. What's the best way to have the y-scale extend down to 0 (not below!), while multiplicatively padding the top of the y scale?

Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
  • 1
    Have a look at @Rosen Matev's asymmetric padding function at [how to expand axis asymmetrically](http://stackoverflow.com/questions/22480052/how-to-expand-axis-asymmetrically-with-ggplot2-without-setting-limits-manually) – Sandy Muspratt Dec 17 '15 at 20:27
  • 1
    @SandyMuspratt thanks! That's exactly what I'm looking for. Also a dupe. – Gregor Thomas Dec 17 '15 at 20:36
  • Rosen Matev's solution broke with ggplot 2.0. I offer a really clunky solution [here](http://stackoverflow.com/questions/34623780/asymmetric-expansion-of-limits-ggplot2-2-0/37695022#37695022). – Sandy Muspratt Jun 08 '16 at 06:47

1 Answers1

3

You could create an extra data set with a single point for each facet and plot it invisibly with geom_blank(). The point is chosen to be a fixed factor larger than the maximum value in the given facet. Here, I choose that factor to be 1.5 to make the effect clearly visible:

max_data <- aggregate(y ~ var, data = data, FUN = function(y) max(y) * 1.5)
max_data <- transform(max_data, x = 2000)

p + geom_blank(data = max_data)

And this is what I get:

enter image description here

Stibu
  • 15,166
  • 6
  • 57
  • 71
  • This works well (+1!) but I'm optimistically hoping for something that could be added to a plot - I'd love it if I could incorporate this behavior as part of a theme. – Gregor Thomas Dec 17 '15 at 20:22