【问题标题】:Vertically align faceted ggplots of different heights when using coord_equal()使用 coord_equal() 时垂直对齐不同高度的多面 ggplots
【发布时间】:2018-02-24 10:44:23
【问题描述】:

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

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)

【问题讨论】:

  • 这个question 对于当前的例子来说可能有点矫枉过正,但可以在答案中找到一些非常好的见解。
  • 你试过patchwork 包吗? library(patchwork); plot1 / plot2 软件包不在 CRAN 上(还),要安装它,运行 library(devtools); devtools::install_github("thomasp85/patchwork")

标签: r ggplot2 gtable cowplot


【解决方案1】:

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

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

【讨论】:

  • 所以你建议修改 egg::gtable_frame() 吗?我猜这是由 egg::ggarrange() 调用的?我想我可以向包的维护者建议这个改变?我不确定这个“修复”是通用的还是应该只是需要固定/相等坐标时的一个选项。
  • 我已经向 egg 的维护者提出了这个修复建议。
【解决方案2】:

主要问题是plot1plot2 具有不同的纵横比。 这是plot1

还有这个plot2

您可以尝试使用 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))

希望它有用。

【讨论】:

  • 这并不能解决问题。关键是要保持两个图的纵横比。
猜你喜欢
  • 2018-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-21
  • 2014-03-30
  • 1970-01-01
  • 2015-05-26
  • 1970-01-01
相关资源
最近更新 更多