Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

r - 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 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...