Home > Enterprise >  Rescaling y axis in facet_grid but keep starting from 0
Rescaling y axis in facet_grid but keep starting from 0

Time:10-26

I'm making a ggplot2 line graph over multiple groups, separating them by using facet_grid.

dat <- data.frame(date = c(1:5, 1:5),
           type = rep(c("A", "B"), each = 5),
           value = c(4500, 4800, 4600, 4900, 4700,
                     1500, 1510, 1500, 1400, 1390)
           )
library(ggplot2)
dat |> 
    ggplot(aes(date, value, group = type))  
    geom_line()  
    facet_wrap(~type)

I'd now like to rescale the y-axis so that it starts from 0 in both cases, but it reaches the maximum values for that specific group.

I tried setting the scales = argument as free_y - this fixes the upper part of the y scale, but unfortunately it has the unwanted effect of not starting from 0:


dat |> 
    ggplot(aes(date, value, group = type))  
    geom_line()  
    facet_wrap(~type, scales = "free_y")

Any ideas how to fix this?

Created on 2022-10-25 with reprex v2.0.2

CodePudding user response:

This could be achieved by fixing the limits of the scale at the lower end using scale_y_continuous(limits = c(0, NA)):

dat <- data.frame(date = c(1:5, 1:5),
                  type = rep(c("A", "B"), each = 5),
                  value = c(4500, 4800, 4600, 4900, 4700,
                            1500, 1510, 1500, 1400, 1390)
)
library(ggplot2)

dat |> 
  ggplot(aes(date, value, group = type))  
  geom_line()  
  scale_y_continuous(limits = c(0, NA))  
  facet_wrap(~type, scales = "free_y")

  • Related