scaling y-axes while using facet_wrap in ggplot

Viewed 211

I am trying to combine different y-axes while using facet_wrap, but I want all the y-axes to have exactly 3 breaks based in the min and max of that scale, so 0, mid-point, and maximum. It works for some of the plots on the facet grid but not all of them.

Here is the current code:

# data table, in long format 
dt = structure(list(Grp = c(rep("GroupA",12),rep("GroupB",12),rep("GroupC",12),rep("GroupD",12)), Type = c(rep(c(rep("Type1",5),rep("Type2",7)),4)), XVal = c(2L, 3L, 4L, 5L, 6L,
1L, 2L, 3L, 4L, 5L, 6L, 7L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L,
5L, 6L, 7L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 2L,
3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 7L), YVal = c(0.2417, 0.2156, 0.264, 
0.2805, 0.2414, 0.2882, 0.0825, 0.0561, 0.1443, 0.1074, 0.0252, 
1e-04, 0.0186, 0.0157, 0.0473, 0.13, 0.1205, 0.0689, 0.1506, 
0.2945, 0.3098, 0.1474, 0.3408, 0.1327, 0.0102, 0.0033, 0.0021, 
2e-04, 0, 0.0124, 0.0053, 0.0039, 0.0014, 4e-04, 0, 0, 0.0574, 
0.1003, 0.0687, 0.0976, 0.1067, 0.1161, 0.0964, 0.0517, 0.0658, 
0.0654, 0.0241, 0.0021)), row.names = c(NA,-48L), class = "data.frame")

# first created a function to define three breaks, and round to 2 decimal points
my_breaks <- function(y) {round(seq(0, max(y),length.out = 3),2)}

# use that function in the 'scale_y_continuous' while specifying that the y scale is "free" in facet_wrap 
ggplot(dt,aes(x=XVal,y=YVal)) + geom_line(aes(color=Type)) +
  facet_wrap(~Grp,scales = "free_y", ncol = 2) +
  scale_y_continuous(breaks = my_breaks)

The breaks are what I want for Groups A & D but not B & C. Any help would be greatly appreciated.

Facet_wrap plot, looking to change y-axis for Groups B & C

1 Answers

It looks like it has something to do with how the rounding is affecting the results of your my_breaks function. If you remove the round so your function looks like

my_breaks <- function(y) {seq(0, max(y),length.out = 3)}

Each facet has exactly three evenly spaced breaks. Now we can format the numbers in the plot:

ggplot(dt,aes(x=XVal,y=YVal)) + geom_line(aes(color=Type)) +
      facet_wrap(~Grp,scales = "free_y", ncol = 2) +
      scale_y_continuous(breaks = my_breaks,
                         labels = function(x){round(x,2)})

enter image description here

Notice, however that in Group C, the labels end up not making total sense, since both values for the breaks (0.013 and 0.006) round to 0.01.

Related