1

I have created one monthly plot with facet_wrap

enter image description here.

So in the plot I have 3 rows and 4 columns. Now I want to set my common y axis for each rows e.g 1st row should have one common y values, same goes with the 2nd and 3rd rows.

I tried but not able to do it.

I used

ggplot(data = PB, 
       aes(x = new_date, y = Mean, group = 1)) +         
  geom_line(aes(color = experiment)) +                        
  theme(legend.title = element_blank()) + 
  facet_wrap( ~MonthAbb, ncol = 4, scales = "free")
Z.Lin
  • 28,055
  • 6
  • 54
  • 94

2 Answers2

1

The issue is the scales = "free". Remove this and it will set a common scale across rows and columns (or use "free_y" or "free_x" to adjust accordingly).

If what you're looking for is a separate scale for each row, it will require a bit more work. Check this solution at R: How do I use coord_cartesian on facet_grid with free-ranging axis which layers invisible points on the plot to force the look you want. Otherwise a simple solution might to look at using gridExtra and plot each row separately, then merge into a grid.

Edit: a gridExtra solution would look something like:

library(gridExtra)

g1 <- ggplot(data = PB1, aes(x=new_date, y = Mean, group = 1)) +
    geom_line(aes(color = experiment)) + 
    theme(legend.title = element_blank())
g2 <- ggplot(data = PB2, aes(x=new_date, y = Mean, group = 1)) +
    geom_line(aes(color = experiment)) + 
    theme(legend.title = element_blank())

grid.arrange(g1, g2, nrow=2)
LRRR
  • 456
  • 3
  • 8
0

Here is an option to set these on a per-panel basis. It is based on a function I've put in a github package. I'm using some dummy data as example.

library(ggplot2)
library(ggh4x)

df <- data.frame(
  x = rep(1:20, 9),
  y = c(cumsum(rnorm(60)) + 90,
        cumsum(rnorm(60)) - 90,
        cumsum(rnorm(60))),
  row = rep(LETTERS[1:3], each = 60),
  col = rep(LETTERS[1:3], each = 20)
)

ggplot(df, aes(x, y)) +
  geom_line() +
  facet_wrap(row ~ col, scales = "free_y") +
  facetted_pos_scales(
    y = rep(list(
      scale_y_continuous(limits = c(90, 100)),
      scale_y_continuous(limits = c(-100, -80)),
      scale_y_continuous(limits = c(0, 20))
    ), each = 3)
  )

enter image description here

teunbrand
  • 33,645
  • 4
  • 37
  • 63