I have this data
library(ggplot2)
dat = data.frame(x = c(1,2,1,2),
group = c("a","a","b","b"),
y = c(10,20,1000,2000))
ggplot(dat, aes(x = x, y = y)) +
geom_point() +
geom_line() +
facet_wrap(~group, ncol = 1) +
coord_cartesian(ylim = c(0, 30))
You can see the B group does not show up because I set the y limit to 0,30
. I want to manually set the individual y limits for each chart. I do NOT want to use scales = "free_y"
because I need control over the limits in each chart.
Is there a way this can be done? Can you somehow supply y limits for each chart in a facet wrap?
To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.
Use scale_xx() functions It is also possible to use the functions scale_x_continuous() and scale_y_continuous() to change x and y axis limits, respectively.
facet_wrap() makes a long ribbon of panels (generated by any number of variables) and wraps it into 2d. This is useful if you have a single variable with many levels and want to arrange the plots in a more space efficient manner. You can control how the ribbon is wrapped into a grid with ncol , nrow , as.
The facet_grid() function will produce a grid of plots for each combination of variables that you specify, even if some plots are empty. The facet_wrap() function will only produce plots for the combinations of variables that have values, which means it won't produce any empty plots.
Unless you want to decrease your plotting area (i.e. not plot some points), you can still have "full" control over your y limits while using scales = "free_y"
.
You can use the same trick I have given to answer your other question: how to set limits on rounded facet wrap y axis?
dat <- data.table(dat)
dat[,y_min := y*0.5, by = group]
dat[,y_max:= y*1.5, by = group]
ggplot(dat, aes(x = x, y = y)) +
geom_point() +
geom_line() +
facet_wrap(~group, ncol = 1, scales = "free_y") +
geom_blank(aes(y = y_min)) +
geom_blank(aes(y = y_max))
For others reading this question, trick is to explicitly create y_min
and y_max
variables for each group. And "plot" them via geom_blank()
. (Nothing is actually plotted, but each facet's plotting area is adjusted based on y_min
and y_max
values for that group).
If for some reasons, you want to manually give min and max (instead of a rule), none is stopping you. But it is tedious:
dat[group == "a",y_min := 0]
dat[group == "a",y_max := 30]
dat[group == "b",y_min := 0]
dat[group == "b",y_max := 3000]
ggplot(dat, aes(x = x, y = y)) +
geom_point() +
geom_line() +
facet_wrap(~group, ncol = 1, scales = "free_y") +
geom_blank(aes(y = y_min)) +
geom_blank(aes(y = y_max))
But, as I have mentioned this works if you want to extend your limits, not decrease them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With