Vertically align faceted ggplots of different heights when using coord_equal()

老子叫甜甜 提交于 2019-12-07 05:02:26

问题


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)


回答1:


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')




回答2:


The main problem is that plot1 and plot2 have different aspect ratios. This is plot1:

And this plot2:

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))

Hope it serves.



来源:https://stackoverflow.com/questions/48961927/vertically-align-faceted-ggplots-of-different-heights-when-using-coord-equal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!