我想使用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)
效果很好,但不幸的是垂直轴线消失了。使用grid.arrange
时不会发生这种情况,但至少对于我的实际数据,x轴没有对齐,因此我希望使用ggarrange
。有没有办法保持轴线?
答案 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
g1 <- ggplotGrob(p1)
gg <- gtable_frame(g1)
grid.newpage()
grid.draw(gg)