Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pad (expand) only the top of continuous scale in ggplot2 [duplicate]

Tags:

r

ggplot2

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?

like image 807
Gregor Thomas Avatar asked Oct 18 '22 20:10

Gregor Thomas


1 Answers

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

like image 114
Stibu Avatar answered Nov 03 '22 01:11

Stibu