I am plotting a graph using ggplot2
and I'd like to have a Y-axis to each separate graph. I get the Y-axis for every graph when I use facet_wrap
, but the layout is not what I want. On the other hand, facet_grid
outputs the exact layout I am looking for, but I can't get the separate Y-axis in each graph.
How can I have the the same layout from facet_grid
but also a Y-axis for each graph as in facet_wrap
?
Here's a simple reproducible example.
Thank you for the input.
# Pkgs
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(ggplot2)
# Generate fake data
set.seed(125)
df = data.frame(
year = c(rep(2017, 3), rep(2018, 3), rep(2019, 3)),
type = rep(c("A", "B", "C"), 3),
month = rep(c("Jan", "Feb", "Mar"), 3),
signal = sample(x = seq(100, 2500, 100), size = 9)
) %>%
mutate(month = factor(month, levels = c("Jan", "Feb", "Mar")))
#Wrapping use facet_wrap........................................
# When I use facet_wrap, I get a Y-axis for each separate graph,
# but then I have a "two-level title" for each graph,
# consisting of year and type.
df %>%
ggplot(aes(x = month, y = signal)) +
geom_point() +
facet_wrap(vars(year, type), scales = "free")
#Wrapping use facet_grid.........................................
# When I use facet_grid, I get a Y-axis for an entire row, and
# this is not what I want. However, the layout is exactly what I want.
df %>%
ggplot(aes(x = month, y = signal)) +
geom_point() +
facet_grid(rows = vars(type),
cols = vars(year),
scales = "free")
Created on 2021-02-17 by the reprex package (v1.0.0)