I am producing a facet chart like this
suppressPackageStartupMessages({
library(tidyverse)
library(scales)
})
set.seed(123456)
test_df <-
tibble(t=1:10,
x=100 runif(10,-10,10),
y=10 runif(10,-4,4),
p=y/x)
test_df |>
pivot_longer(cols=x:p,
names_to = "var",
values_to = "value") |>
mutate(var=factor(var,levels=c("x","y","p"))) ->
test_df_long
test_df_long |>
ggplot(aes(x=t,y=value))
geom_line()
scale_y_continuous(limits=c(0,NA))
facet_wrap(vars(var),ncol=1,
scales = "free_y")
I would like to change the formatting of the labels for the p facet to percent.
I have not found a way to use different labelling functions to different facets.
Can it be done?
CodePudding user response:
You can use the package facetscales
like this:
devtools::install_github("zeehio/facetscales")
library(facetscales)
scales_y <- list(
x = scale_y_continuous(),
y = scale_y_continuous(),
p = scale_y_continuous(labels = percent_format())
)
test_df_long |>
ggplot(aes(x=t,y=value))
geom_line()
scale_y_continuous(limits=c(0,NA))
facet_grid_sc(rows = vars(var), scales = list(y = scales_y))
Output:
CodePudding user response:
You could use ggh4x::facetted_pos_scales()
to control position scales of individual facets. If you just need to adjust a single scale, you could use the formula notation as below. (Disclaimer: I'm the author of ggh4x)
suppressPackageStartupMessages({
library(tidyverse)
library(scales)
})
set.seed(123456)
test_df <-
tibble(t=1:10,
x=100 runif(10,-10,10),
y=10 runif(10,-4,4),
p=y/x)
test_df |>
pivot_longer(cols=x:p,
names_to = "var",
values_to = "value") |>
mutate(var=factor(var,levels=c("x","y","p"))) ->
test_df_long
test_df_long |>
ggplot(aes(x=t,y=value))
geom_line()
scale_y_continuous(limits=c(0,NA))
facet_wrap(vars(var),ncol=1,
scales = "free_y")
ggh4x::facetted_pos_scales(
y = var == "p" ~ scale_y_continuous(labels = percent_format())
)
Created on 2022-05-11 by the reprex package (v2.0.1)