Search code examples
rggplot2facet-wrapfacet-grid

Keeping unit of measure in facet_wrap while scales="free_y"?


I'm trying to create a facet_wrap() where the unit of measure remains identical across the different plots, while allowing to slide across the y axis.

To clearify with I mean, I have created a dataset df:

library(tidyverse)

df <- tibble(
  Year = c(2010,2011,2012,2010,2011,2012),
  Category=c("A","A","A","B","B","B"),
  Value=c(1.50, 1.70, 1.60, 4.50, 4.60, 4.55)
)

with df, we can create the following plot using facet_wrap:

ggplot(data = df, aes(x=Year, y=Value)) + geom_line() + facet_wrap(.~ Category)

Plot 1 Plot1

To clarify the differences between both plots, one can use scale = "free_y":

ggplot(data = df, aes(x=Year, y=Value)) + geom_line() 
 + facet_wrap(.~ Category, scale="free_y")

Plot 2 Plot 2

Although it's more clear, the scale on the y-axis in plot A isequal to 0.025, while being 0.0125 in B. This could be misleading to someone who's comparing A & B next to each other.

So my question right now is to know whether there exist an elegant way of plotting something like the graph below (with y-scale = 0.025) without having to plot two seperate plots into a grid?

Thanks

Desired result: enter image description here Code for the grid:

# Grid
## Plot A
df_A <- df %>%
  filter(Category == "A") 
plot_A <- ggplot(data = df_A, aes(x=Year, y=Value)) + geom_line() +  coord_cartesian(ylim = c(1.5,1.7)) + ggtitle("A")

## Plot B
df_B <- df %>%
  filter(Category == "B") 
plot_B <- ggplot(data = df_B, aes(x=Year, y=Value)) + geom_line()  + coord_cartesian(ylim = c(4.4,4.6)) + ggtitle("B")

grid.arrange(plot_A, plot_B, nrow=1)

Solution

  • Based on the info at Setting individual y axis limits with facet wrap NOT with scales free_y you can you use geom_blank() and manually specified y-limits by Category:

    # df from above code
    df2 <- tibble(
      Category = c("A", "B"),
      y_min = c(1.5, 4.4),
      y_max = c(1.7, 4.6)
    )
    
    df <- full_join(df, df2, by = "Category")
    
    ggplot(data = df, aes(x=Year, y=Value)) + geom_line() + 
      facet_wrap(.~ Category, scales = "free_y") +
      geom_blank(aes(y = y_min)) +
      geom_blank(aes(y = y_max))
    

    ggplot2 figure with scales going from 1.5 to 1.7 for A and 4.4 to 4.6 for B