0

I have a faceted ggplot like so:

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')

Problem is that the y-axes values for group 2 are all identical because they only differ in the 6-7th decimal. So I tried

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())

but that adds a lot of unnecessary decimals for the first group (duh!).

Is there any way to make ggplot show however many decimal places are necessary for the values on the y-axis to all be different for all facets? Or is doing this manually with gridExtra my best bet here?

RoyalTS
  • 9,545
  • 12
  • 60
  • 101
  • I guess this is similar but perhaps not identical: http://stackoverflow.com/questions/11585954/varying-axis-labels-formatter-per-facet-in-ggplot-r – RoyalTS Feb 17 '14 at 13:11

1 Answers1

6

This seems to work:

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

Roland
  • 127,288
  • 10
  • 191
  • 288
  • Excellent! For more general setting such as mine it might make sense to make the third line `d <- log10(min(diff(x),na.rm=TRUE))` so it doesn't trip over missing values. – RoyalTS Feb 17 '14 at 14:36
  • @RoyalTS There shouldn't be any missing values in `x`. – Roland Feb 17 '14 at 14:41
  • In my reproducible example that's true. But in real-world datasets such as mine, there may well be `NA`s and these will mess up your solution because if there are that's what `d` will be. – RoyalTS Feb 17 '14 at 15:41
  • Umm, no. Non of your axis breaks should be `NA` and `x` are the axis breaks. – Roland Feb 17 '14 at 15:43
  • Huh. If I don't put the `na.rm=TRUE` in there I get `Error: missing value where TRUE/FALSE needed`. – RoyalTS Feb 17 '14 at 15:48
  • Can you add `print(x)` at the top of the function and check these values? – Roland Feb 17 '14 at 15:51
  • A sample (sorry about the shitty formatting): [1] NA -1550 -1525 -1500 NA [1] -1486.8 -1486.7 -1486.6 -1486.5 -1486.4 -1486.3 [1] NA -1486.285 -1486.285 -1486.285 – RoyalTS Feb 17 '14 at 15:55
  • That surprises me. Well, if it works with `na.rm=TRUE` that's not a real problem. – Roland Feb 17 '14 at 15:59