# Custom axis transformations in ggplot2

August 14, 2012
By

(This article was first published on NumberTheory » R stuff, and kindly contributed to R-bloggers)

To apply a data transformation on an axis in a ggplot, you can use coordinate transformations. For more detail see the ggplot2 documentation. A number of coordinate transformations is available, including log10 and sqrt. However, if you want to perform a custom transformation this is not trivial. Say the transformation involves x = 1/x. To get this transformation available you can define the following function (see ?trans_new for more details):

require(scales) # trans_new() is in the scales library
one_over_trans = function() trans_new("one_over", function(x) 1/x, function(x) 1/x)

from now one you can use one_over as a coordinate transform. Note that the name convention is nameoftrans_trans. Example code:

qplot(carat, price, data=diamonds) + coord_trans(x = "log10", y = "one_over")