Dan*_* C. 5 r ggplot2 r-grid cowplot
我正在安排2x2地块。这些图共享相同的轴,所以我想将它们放在一起,例如
这段代码:
library(ggplot2)
library(cowplot)
Value <- seq(0,1000, by = 1000/10)
Index <- 0:10
DF <- data.frame(Index, Value)
plot <- ggplot(DF, aes(x = Index, y = Value)) +
geom_line(linetype = 2) +
theme(aspect.ratio = 0.5)
plot_grid(plot, plot, plot, plot, align = "hv", ncol = 2)
Run Code Online (Sandbox Code Playgroud)
产生
但我想要类似的东西:
如何获得类似的结果?
我认为这是包中的ggarrange()功能的一个案例egg。这样做plot_grid()需要无休止的摆弄并且不值得。
(技术原因是plot_grid()保持网格中每个地块的总面积不变,但如果一些地块有 x 轴而其他地块没有,那么它们占据不同的区域。可以尝试通过使用rel_heights参数来规避这一点,但有没有好的方法来计算 的正确值rel_heights,所以这将是反复试验。相比之下,ggarrange()分别查看绘图面板和周围的元素,并确保绘图面板具有相同的大小。)
这是使用的代码ggarrange():
Value <- seq(0,1000, by = 1000/10)
Index <- 0:10
DF <- data.frame(Index, Value)
pbase <- ggplot(DF, aes(x = Index, y = Value)) +
geom_line(linetype = 2) +
theme_bw()
ptopleft <- pbase +
scale_x_continuous(position = "top") +
theme(plot.margin = margin(5.5, 0, 0, 5.5),
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank())
ptopright <- pbase +
scale_y_continuous(position = "right") +
scale_x_continuous(position = "top") +
theme(plot.margin = margin(5.5, 5.5, 0, 0),
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank())
pbottomleft <- pbase +
theme(plot.margin = margin(0, 0, 5.5, 5.5))
pbottomright <- pbase +
scale_y_continuous(position = "right") +
theme(plot.margin = margin(0, 5.5, 5.5, 0))
library(egg)
ggarrange(ptopleft, ptopright,
pbottomleft, pbottomright,
ncol = 2)
Run Code Online (Sandbox Code Playgroud)
两条评论:
要删除顶部绘图上绘图面板下方的最后一点空间,我们需要将 x 轴移动到顶部,即使我们没有显示它。这是主题机制的一个奇怪的限制。我们不能完全摆脱一个轴。
我不是共享轴标题的忠实粉丝,就像你的例子一样。我认为每个轴都应该有一个标题。如果您想要共享轴标题,为什么不使用分面机制?