Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align an ordinary ggplot with a faceted one in cowplot?

Tags:

I'm trying to arrange plots for publication with the use of cowplot package.
I just want the panels to be equally sized and labelled.

Reproducible example

library(ggplot2)
library(cowplot)

gg1 <- ggplot(mtcars)+
        geom_point(aes(x=mpg,y=hp))+
        theme_bw()+
        theme(aspect.ratio=1)

gg2 <- ggplot(mtcars)+
        geom_point(aes(x=mpg,y=hp,fill=cyl))+
        facet_wrap(~cyl,ncol=2)+
        theme_bw()+
        theme(aspect.ratio=1,
              legend.position='none')

output <- plot_grid(gg1,gg2, labels = c('A','B'),label_size = 20)
print(output)

The code produces this plot. enter image description here

As you may see, neither the horizontal axises match nor do the upper edges of the panels.

The argument align from cowplot does not work with faceted plots.

Any ideas?

like image 862
ikashnitsky Avatar asked Aug 29 '15 16:08

ikashnitsky


1 Answers

Since this is one of the highest voted question regarding cowplot and complex alignments, I wanted to point out that cowplot now does have some functionality for aligning faceted plots. (I'm the package author.) However, they don't work in this particular case!

For example, this works (using the axis option in plot_grid()):

gg1 <- ggplot(mtcars) +
  geom_point(aes(x=mpg, y=hp)) +
  theme_bw()

gg2 <- ggplot(mtcars)+
  geom_point(aes(x=mpg, y=hp, fill=cyl)) +
  facet_wrap(~cyl, ncol=2) +
  theme_bw() +
  theme(legend.position='none')

plot_grid(gg1, gg2, labels = c('A','B'), label_size = 20,
          align = 'h', axis = 'tb')

enter image description here

We can also do this the following, to get a different type of alignment (depending on whether you want the facet strip to be counted as part of the plot or not):

plot_grid(gg1, gg2, labels = c('A', 'B'), label_size = 20,
          align = 'h', axis = 'b')

enter image description here

Now why did I say it doesn't work for this case? Because, if you look at the original code in the question, you'll see that there was a theme(aspect.ratio=1) setting that I removed. cowplot can align plots as long as you don't force a specific aspect ratio, because the method it uses to align plots typically modifies the aspect ratio of the individual plots.

like image 51
Claus Wilke Avatar answered Oct 11 '22 10:10

Claus Wilke