I am trying to plot three different subplots within the same graphic using facet_wrap
. I know the y
axis can be settled "free" or "fixed" with the argument scales
of facet_wrap()
. However, due to the characteristics of my data, I would like to keep the y
axis fixed for the first two plots but re-scaled for the third one. I could do three individual plots and arrange them together, but as I am using this code inside a Shiny app this is not the most convenient. Below you will find a minimal example of my data and my code so far.
##Data example:
Color Time Metric
1 Green 0 200.00
2 Green 2 300.00
3 Green 4 600.00
4 Green 6 800.00
5 Green 8 1400.00
6 Green 10 2600.00
7 Red 0 150.00
8 Red 2 260.00
9 Red 4 400.00
10 Red 6 450.00
11 Red 8 600.00
12 Red 10 650.00
13 Yellow 0 0.10
14 Yellow 2 0.20
15 Yellow 4 0.30
16 Yellow 6 0.60
17 Yellow 8 0.55
18 Yellow 10 0.70
#With free scales
ggplot(Example) + geom_point(aes(x = Time, y = Metric)) + facet_wrap(facets = "Color", scales = "free")
#With fixed scales:
ggplot(Example) + geom_point(aes(x = Time, y = Metric)) + facet_wrap(facets = "Color", scales = "fixed")
As you see, neither alternative is really useful: if I set the scales as free
I lose the comparison between Green
and Red
, which are approximately within the same ranges. However, if I set them as fix
then it is impossible to see what is going on with Yellow
. The ideal would be to have Green
and Red
on the same scale, and yellow
in its own scale. Can this be done with facet_wrap()
?
Consider this like an option for you, but it uses a variant of facet_grid()
found in package facetscales
which allows you to define specific scales. Here the code:
#Install
#devtools::install_github("zeehio/facetscales")
library(tidyverse)
library(facetscales)
#Define scales
scales_y <- list(
`Green` = scale_y_continuous(limits = c(0, 2700)),
`Red` = scale_y_continuous(limits = c(0, 2700)),
`Yellow` = scale_y_continuous(limits = c(0, 0.7))
)
#Code
ggplot(Example) +
geom_point(aes(x = Time, y = Metric)) +
facet_grid_sc(Color~.,
scales = list(y = scales_y))
Output:
Some data used:
#Data
Example <- structure(list(Color = c("Green", "Green", "Green", "Green",
"Green", "Green", "Red", "Red", "Red", "Red", "Red", "Red", "Yellow",
"Yellow", "Yellow", "Yellow", "Yellow", "Yellow"), Time = c(0L,
2L, 4L, 6L, 8L, 10L, 0L, 2L, 4L, 6L, 8L, 10L, 0L, 2L, 4L, 6L,
8L, 10L), Metric = c(200, 300, 600, 800, 1400, 2600, 150, 260,
400, 450, 600, 650, 0.1, 0.2, 0.3, 0.6, 0.55, 0.7)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18"))