Home > database >  Define custom transformation of ggplot axis labels with trans_new function
Define custom transformation of ggplot axis labels with trans_new function

Time:01-13

I am working on percentage changes between periods and struggling with logaritmic transformation of labels. Here is an example based on the storms dataset:

library(dplyr)
library(ggplot2)
library(scales)

df <- storms |>
  group_by(year) |>
  summarise(wind = mean(wind)) |>
  mutate(lag = lag(wind, n = 1)) |>
  mutate(perc = (wind / lag) - 1) |>
  tidyr::drop_na()

I want to visualize the distribution of percentages, making the percentage change symmetrical (log difference) with log1p.

ggplot(df, aes(x = log1p(perc)))  
  geom_histogram(bins = 5) 

enter image description here

Note that although the histogram remains symmetrical in shape, the axis labels represent the back-transformed values of the original axis labels.

The point of a transformer object is to do all this for you without having to pass a transformed data set (i.e. without having to pass log1p(perc)). So in your case, you could do:

trans_perc <- trans_new(
  name      = "trans_perc",
  transform = log1p,
  inverse   = expm1,
  format    = percent_format(),
  domain    = c(-Inf, Inf)
)

ggplot(df, aes(x = perc))  
  geom_histogram(bins = 5)  
  scale_x_continuous(trans = trans_perc)

enter image description here

Which gives essentially the same result

  • Related