2

In the following code, I am able to set two different scales for two facets. Now, I want to format the big scale (e.g. turn it into dollar with scale_y_continuous(labels = dollar)). How do I format individual facet's scale?

df <- data.frame(value = c(50000, 100000, 4, 3),
                 variable = c("big", "big", "small", "small"),    
                 x = c(2010, 2011, 2010, 2011))
ggplot(df) + geom_line(aes(x, value)) + facet_wrap(~ variable, scales = "free_y")

A similar question a long time ago about setting individual limit has no answer. I was hoping that ggplot2 2.0 has done something about this.

Community
  • 1
  • 1
Heisenberg
  • 8,386
  • 12
  • 53
  • 102

1 Answers1

3

The function scale_y_continuous allows for functions to be used for the labels argument. We can create a custom labeler that uses the minimum big value (or any other) as a threshold.

dollar <- function(x) {
  ifelse(x >= min(df$value[df$variable == "big"]),
    paste0("$", prettyNum(x, big.mark=",")), x)
}

ggplot(df) + geom_line(aes(x, value)) + facet_wrap(~ variable, scales = "free_y") +
  scale_y_continuous(labels = dollar)

enter image description here

Pierre L
  • 28,203
  • 6
  • 47
  • 69
  • Very clever, though localized to my example in which the `big` and `small` values are separable. I suppose this means there is no way to tell ggplot2 I want `labeller1` for this facet, and `labeller2` for that facet? – Heisenberg Feb 10 '17 at 21:37
  • Not to my knowledge. – Pierre L Feb 10 '17 at 21:39