R – ggplot2 axis transformation by constant factor

ggplot2r

In a ggplot2 density plot (geom_density) I have the following y-axis labels

  • 0.000
  • 0.005
  • 0.010
  • 0.015
  • 0.020

What is the correct way to change them to something like

  • 0
  • 5
  • 10
  • 15
  • 20

possibly with the automatic adding of "10^3 x density" to the label. In the past I've just multiplied my data and manually changed the label, but in this case the y-axis data is generated for me by the density plot.

I'm aware that I can write things like scale_y_continuous(trans="log10"), but have not found any way to do a simple multiplicative constant, or define a custom transform.

Best Answer

This answer is out of date for ggplot2 version 0.90. Now, the same format would be specified (much more neatly) this way:

scale_y_continuous(labels=function(x)x*1000)

or if you want to use the same labelling scheme multiple times:

formatter1000 <- function(){
  function(x)x*1000
}

scale_y_continuous(labels=formatter1000())

Note that if you are specifying axis limits using the xlim and ylim functions, this might not work. Instead, use the scale_y_continuous(..., limits=c(0, 1)) specification.

There are also a bunch of built in formats in the scales package, including comma formatting, percentage formatting, dollar formatting and scientific notation formatting. See its documentation for more details.

Hope that helps someone out there, as this change certainly confused me!

Related Topic