Custom axis transformations in ggplot2

August 14, 2012

(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")

To leave a comment for the author, please follow the link and comment on their blog: NumberTheory » R stuff. offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...

If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)