2014-02-17 26 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