使用ggarrange时如何避免轴线消失?

时间:2017-06-07 09:54:38

标签: r ggplot2 facet

我想使用ggarrange排列两个方面图(为了使x轴对齐)。

library(egg)
library(ggplot2)

p1 <- ggplot(warpbreaks) +
  geom_bar(aes(x = wool)) +
  facet_wrap(~tension, ncol = 2, scales = "free_x") +
  theme_bw() +
  theme(axis.line = element_line(colour = "black", size = .1),
        panel.border = element_blank(),
        strip.background = element_blank())

p2 <- ggplot(warpbreaks) +
  geom_bar(aes(x = tension)) +
  facet_wrap(~wool) +
  theme_bw() +
  theme(axis.line = element_line(colour = "black", size = .1),
        panel.border = element_blank(),
        strip.background = element_blank())

ggarrange(p1, p2, ncol = 2)

enter image description here

效果很好,但不幸的是垂直轴线消失了。使用grid.arrange时不会发生这种情况,但至少对于我的实际数据,x轴没有对齐,因此我希望使用ggarrange。有没有办法保持轴线?

1 个答案:

答案 0 :(得分:4)

tl; dr:设置panel.background = element_blank()应恢复轴。

我认为它是ggplot2中剪辑问题的组合(y轴线可以通过绘图面板剪切,将其宽度减半),egg :: gtable_frame将轴放置在绘图面板下方。

library(egg)
library(ggplot2)

p1 <- ggplot(warpbreaks) +
  geom_bar(aes(x = wool)) +
  facet_wrap(~tension, ncol = 2, scales = "free_x") +
  theme_bw() +
  theme(axis.line = element_line(colour = alpha("red", 0.5), size = 5),
        panel.border = element_blank(),
        panel.background = element_rect(fill = alpha("white", 0.5), 
                                        linetype = 2, colour = "black"),
        strip.background = element_blank())

p1

enter image description here

g1 <- ggplotGrob(p1)
gg <- gtable_frame(g1)
grid.newpage()
grid.draw(gg)

enter image description here