ggplot2 axis transformation by constant factor
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 th开发者_JAVA百科e 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.
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!
You could add the scale_y_continuous(formatter='formatter1000')
with the following function defined before:
formatter1000 <- function(x){
x*1000
}
Please note, that the above answer was given one and a half year ago with a prior ggplot version. With the latest release (0.9) of ggplot the above example is not working, please try something like: scale_y_continuous(labels = formatter1000)
精彩评论