2014-02-17 32 views
0

我有一个刻面ggplot像这样:在ggplot面轴小数的智能号标签

library(ggplot2) 
grid <- seq(-10,10,length.out=1000) 
df <- data.frame(x=rep(grid,2),y=c(grid^2,100+grid^2/100000000),group=rep(c(1,2),each=length(grid))) 
ggplot(df,aes(x,y)) + geom_line() + facet_wrap(~group,scales='free') 

问题是,对于组2中的y轴的值都是相同的,因为它们只在6-7th不同小数。所以我试了

fmt <- function(){ 
    function(x) format(x,nsmall = 7,scientific = FALSE) 
} 
ggplot(df,aes(x,y)) + geom_line() + facet_wrap(~group,scales='free') + scale_y_continuous(labels = fmt()) 

但是,第一组(duh!)增加了很多不必要的小数。

有没有什么办法让ggplot显示然而,许多小数位数所必需的所有在y轴上的值各方面有所不同?或者是在gridExtra这里我最好的选择呢?

+0

我想这是类似的,但可能不相同:http://stackoverflow.com/questions/11585954/varying-axis-labels-formatter-每个小功能于ggplot-R – RoyalTS

回答

5

这似乎工作:

fmt <- function(){ 
    function(x) { 
    d <- log10(min(diff(x))) 
    if(d < 0) format(x,nsmall = abs(round(d)),scientific = FALSE) else x 
    } 
} 
ggplot(df,aes(x,y)) + geom_line() + 
    facet_wrap(~group,scales='free') + scale_y_continuous(labels = fmt()) 

enter image description here

+0

好极了!对于更一般的设置诸如矿井它可能是有意义的使第三行'd < - 日志10(分钟(差异(x)中,na.rm = TRUE))'所以它不会被绊倒的缺失值。 – RoyalTS

+0

@RoyalTS'x'中不应该有任何缺失的值。 – Roland

+0

在我的可重复的例子中是这样。但在现实世界中的数据集,如矿山,有可能是'NA's这些会搞乱你的解决方案,因为如果有那就是'D'会。 – RoyalTS