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
1.1k views
in Technique[技术] by (71.8m points)

r - ggplot2 y axis label decimal precision

I am plotting several ggplot charts in a loop (i know, i know don't loop use plyr...but) and was curious if there was a way to set the decimal precision to say one decimal (i.e. 0.0). I am using the following scale transformation.

p <- p + scale_y_log10()

Any help would be appreciated.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

I was kind of under the impression that one decimal (i.e 1.2) was the default, but if you're seeing more decimal places than that, you can pass your own formatting to the scale:

fmt_dcimals <- function(decimals=0){
   # return a function responpsible for formatting the 
   # axis labels with a given number of decimals 
   function(x) as.character(round(x,decimals))
}

And then add the scale to your plot:

ggplot( ... ) + scale_y_log10(labels = fmt_dcimals(2))

Now that I think about this, I should add that if you're really going to write your own formatter, you should probably stick to using the format function to do the work, rather than rounding and coercing. That's probably safer and "nicer".

As an example, to force two digits after the decimal, you could change this formatting function to something like this:

fmt_dcimals <- function(decimals=0){
    function(x) format(x,nsmall = decimals,scientific = FALSE)
}

and you can further play with the nsmall and digits arguments to format to get what you want, I think. An example of it's use:

df <- data.frame(x = 1:5,y = rexp(5))
ggplot(df,aes(x = x,y=y)) + 
    geom_point() + 
    scale_y_log10(labels = fmt_dcimals(2))

enter image description here


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

...