It's me again
It's me again

Reputation: 65

Mixing facet_grid() and facet_wrap() in ggplot2

My question is a bit strange. I have four methods (M1, M2, M3, and M4) that each has been experimented in two independent phases (T1, and T2), and 10 different sizes (1, 2, ..., 10). The following table shows the structure of the data:

phase size  mean      stdev   method
T1    1     0.005     0.001    M1
T1    2     0.009     0.004    M1
T1    3     0.011     0.004    M1
...
T2    9     269.020   12.003   M4
T2    10    297.024   10.004   M4

The range of the first phase results (T1) is smaller than those of the second phase. The following command generates the first plot

p <- ggplot(ds, aes(x=size, y=mean, color=method)) 
      + geom_line() 
      + geom_smooth(aes(ymin=mean-stdev, ymax=mean+stdev), stat="identity") 
      + scale_x_discrete(breaks=1:10) 
      + labs(x="Size", y="Time in Seconds", fill="Method") 
      + theme(panel.margin=unit(0.5, "lines"), legend.position="none") 
      + facet_grid(method~phase, scales="free_y")

The result: The use of facet_grid()
While the following code gives the second figure

p <- ggplot(ds, aes(x=size, y=mean, color=method))
      + geom_line() 
      + geom_smooth(aes(ymin=mean-stdev, ymax=mean+stdev), stat="identity") 
      + scale_x_discrete(breaks=1:10) 
      + labs(x="Size", y="Time in Seconds", fill="Method") 
      + theme(panel.margin=unit(0.5, "lines"), legend.position="none") 
      + facet_wrap(method~phase, ncol=2, scales="free_y")

The use of facet_wrap()
Now, the question is "How can I use the facet_grid() and forcing the y-axes to be free similar to the use of facet_wrap()?" or "How to change the labels of facet_wrap() to be similar to facet_grid()?"
Thank you in advance

Upvotes: 4

Views: 1778

Answers (1)

BrodieG
BrodieG

Reputation: 52687

EDIT: word of warning for others, the data the OP is using but hasn't included has enough dynamic range in the low values that this answer will not work.

I don't think you can do exactly what you want with facet_grid, but you can get pretty close in your particular implementation if you're willing to swap M and T:

ggplot(ds, aes(x=size, y=mean, color=method)) + geom_line() + 
  #geom_smooth(aes(ymin=mean-stdev, ymax=mean+stdev), stat="identity") + 
  scale_x_discrete(breaks=1:10) + 
  labs(x="Size", y="Time in Seconds", fill="Method") +
  theme(panel.margin=unit(0.5, "lines"), legend.position="none") + 
  facet_grid(phase~method, scales="free_y")

enter image description here

In facet_grid, the Y scales are free across rows, but not columns, so by re-orienting your faceting we can segregate the high magnitude and low magnitude values onto rows so that the row-wise freeing has the desired effect.

Upvotes: 1

Related Questions