5

I am trying to combine two FACETED ggplot objects with coord_equal() using cowplot::plot_grid() or egg::ggarrange() and vertically align them.

The egg::ggarrange() approach works fine for UNFACETED plots, with the solution posted here.

However, the egg::ggarrange() solution breaks down when faceting is included. The plots are correctly aligned, but the units of the y-axes are twice as large as those of the x-axes. Any suggestions for how to generalize this for faceting?

dat1 <- data.frame(x = rep(1:10, 2), y = 1:20, z = rep(c("A", "B"), 10))
dat2 <- data.frame(x = 1:10, y = 1:10, z = rep(c("A", "B"), 5))
plot1 <- ggplot(dat1, aes(x=x, y=y)) + 
  geom_point() + coord_equal() + facet_wrap(~z)
plot2 <- ggplot(dat2, aes(x=x, y=y)) + 
  geom_point() + coord_equal() + facet_wrap(~z)
egg::ggarrange(plot1, plot2, ncol = 1)

image 1

Kevin
  • 491
  • 3
  • 10
  • 2
    This [question](https://stackoverflow.com/questions/48549294/get-same-height-for-plots-having-different-facet-numbers-and-coord-fixed) might be an overkill for the current example but some very nice insights can be found in the answer. – missuse Feb 24 '18 at 11:06
  • Have you tried the `patchwork` package? `library(patchwork); plot1 / plot2` The packages is not on CRAN (yet), to install it, run `library(devtools); devtools::install_github("thomasp85/patchwork")` – markus Feb 24 '18 at 11:11

2 Answers2

3

it seems to be a simple fix,

library(egg)

b <- body(gtable_frame)
b[6] <- parse(text="if (fixed_ar) {
    ar <- as.numeric(g$heights[tt[1]]) / as.numeric(g$widths[ll[1]])
    height <- width * (ar / length(ll))
    g$respect <- FALSE
}")

body(gtable_frame) <- b

assignInNamespace("gtable_frame", gtable_frame, ns = 'egg')

enter image description here

Claus Wilke
  • 16,992
  • 7
  • 53
  • 104
  • So are you suggesting a modification of egg::gtable_frame()? I'm guessing this is called by egg::ggarrange()? I guess I could suggest this change to the package's maintainer? I'm not sure if this "fix" is universal or should just be an option for when fixed/equal coords are desired. – Kevin Feb 24 '18 at 21:05
  • I've suggested this fix to the maintainer of egg. – Kevin Feb 28 '18 at 11:38
2

The main problem is that plot1 and plot2 have different aspect ratios. This is plot1: enter image description here

And this plot2:

enter image description here

You can try to keep the aspect ratio using, i.e. theme(aspect.ratio=1) instead of coord_equal():

require(ggplot2)
dat1 <- data.frame(x = rep(1:10, 2), y = 1:20, z = rep(c("A", "B"), 10))
dat2 <- data.frame(x = 1:10, y = 1:10, z = rep(c("A", "B"), 5))
plot1 <- ggplot(dat1, aes(x=x, y=y)) + geom_point() + theme(aspect.ratio=1)+
  facet_wrap(~z)
plot2 <- ggplot(dat2, aes(x=x, y=y)) + geom_point() + theme(aspect.ratio=1)+
  facet_wrap(~z)
egg::ggarrange(plot1, plot2, ncol = 1,heights = c(1,10))

enter image description here

Hope it serves.

Mabel Villalba
  • 2,538
  • 8
  • 19