Heisenberg
Heisenberg

Reputation: 8806

How to specify different scales format for different facets?

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.

Upvotes: 2

Views: 1119

Answers (1)

Pierre L
Pierre L

Reputation: 28441

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

Upvotes: 3

Related Questions