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")
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
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?