ggplot2 y轴标签的小数精度 [英] ggplot2 y axis label decimal precision
问题描述
我在一个循环中绘制了几个ggplot图表(我知道,我知道不会循环使用plyr ......但是)并且很好奇,如果有一种方法可以将小数精度设置为一个小数(例如0.0) 。
p < - p + scale_y_log10()
$ c $ >我的印象是,一位小数(即1.2)是默认值,但如果您看到更多的小数位数,那么您可以将自己的格式传递给该位数:
fmt_dcimals< - function(decimals = 0){
#返回一个可响应格式化
#轴标签的函数,小数
函数(x)as.character(round(x,decimals))
}
然后将比例添加到您的图中:
ggplot(...)+ scale_y_log10(labels = fmt_dcimals( 2))
现在我想到了这个,我应该补充一点,如果你真的要编写你自己的格式化程序,你应该坚持使用格式
函数做的工作,而不是四舍五入和强制。这可能更安全和更好。
例如,要在小数点后强制两位数字,可以将此格式化函数更改为如下所示:
fmt_dcimals< - 函数(小数= 0){
函数(x)格式(x,nsmall =小数,科学= FALSE )
}
你可以进一步使用 nsmall
和数字
参数到格式
来获得你想要的,我想。它的一个例子是:
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))
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.
解决方案 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))
这篇关于ggplot2 y轴标签的小数精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!