Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a function to transform axis values with ggplot2?

Instead of 'log2', I want to use 'log2/(log2-1)'

sp <- ggplot(cars, aes(x = speed, y = dist)) + geom_point()
sp
sp + scale_x_continuous(trans='log2') +
  scale_y_continuous(trans='log2')

When I try, I get:

object 'log2/(log2-1)_trans' of mode 'function' was not found

Thanks.

like image 497
Krantz Avatar asked Jan 19 '26 05:01

Krantz


1 Answers

You have to define the function first, and its inverse for the labelling, then use the trans_new function from the scales package:

log2_1 <- function(x) log2(x)/(log2(x)-1)
antilog2_1 <- function(x) 2^(x/(x-1))

sp + scale_x_continuous(trans = trans_new("log2_1", 
                                          transform=log2_1,
                                          inverse=antilog2_1)) +
  scale_y_continuous(trans = trans_new("log2_1", 
                                       transform=log2_1,
                                       inverse=antilog2_1))

enter image description here

like image 165
Edward Avatar answered Jan 20 '26 21:01

Edward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!