ggplot facet轴标签中的智能小数位数

Roy*_*lTS 0 r ggplot2

我有一个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')
Run Code Online (Sandbox Code Playgroud)

问题是第2组的y轴值都是相同的,因为它们仅在第6-7位小数中不同.所以我试过了

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())
Run Code Online (Sandbox Code Playgroud)

但是这为第一组增加了许多不必要的小数(呃!).

是否有任何方法可以ggplot显示,但是y轴上的值需要多个小数位才能对所有方面都有所不同?或者这是gridExtra我最好的选择吗?

Rol*_*and 6

这似乎有效:

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())
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述