使用coord_equal()

时间:2018-02-24 10:44:24

标签: r ggplot2 gtable cowplot

我正在尝试使用coord_equal()cowplot::plot_grid()将两个FACETED ggplot对象与egg::ggarrange()合并,然后垂直对齐它们。

egg::ggarrange()方法适用于UNFACETED图,解决方案已发布here

但是,当包含分面时,egg::ggarrange()解决方案会中断。 图正确对齐,但y轴的单位是x轴的两倍。有关如何将其概括为分面的任何建议吗?

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

2 个答案:

答案 0 :(得分:3)

这似乎是一个简单的修复,

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

答案 1 :(得分:2)

主要问题是plot1plot2具有不同的宽高比。 这是plot1enter image description here

这是plot2

enter image description here

您可以尝试使用宽高比,即theme(aspect.ratio=1)代替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

希望它有用。