For some of my charts I would like to change the formatting of the numbers on the x axis for each facet conditionally on the label of the facet e.g. based on the order of magnitude (e.g. k, M, B etc.).
In the example below with the mtcars
data, I would like the facet with gear==3
to keep the original number, with gear==4
create a "k" format and with gear==5
an "M" format. So that the two latter would be expressed in thousands and millions respectively.
Is is possible to use the label_value
from the labeller
to apply conditionally a format/function?
library(tidyverse)
d<-mtcars%>%mutate(mpg2=ifelse(gear==5,mpg*1000000,mpg))
ggplot(d) +
geom_point(aes(mpg2, cyl)) +
facet_wrap(~ gear, scales = "free")+
scale_x_continuous(name = NULL, labels = function(l) {
return(paste0(round(l / 1000, 1), "K"))
})