ggplot2:对齐不同间距的多个图并在它们之间添加箭头

ika*_*sky 12 r ggplot2 r-grid

我有6个图,我想以两步的方式整齐地排列(见图).最好,我想添加漂亮的箭头.

有任何想法吗?


UPD.当我的问题开始收集负面反馈时,我想澄清一下,我已经检查了所有(部分)相关的问题,并没有发现如何在"画布"上自由定位ggplots.而且,我想不出在绘图之间绘制箭头的单一方法.我不是要求现成的解决方案.请指出方向.

在此输入图像描述

eip*_*i10 15

这是您想要的布局的尝试.它需要手动进行一些格式化,但您可以通过利用绘图布局中内置的坐标系来自动化大部分格式.此外,您可能会发现(grid.curvegrid.bezier我使用的)箭头曲线的形状完全符合您的要求.

我知道这grid很危险,所以我对任何改进建议感兴趣.无论如何,这里......

加载我们需要的包,创建几个实用程序grid对象,并创建一个布局图:

library(ggplot2)
library(gridExtra)

# Empty grob for spacing
#b = rectGrob(gp=gpar(fill="white", col="white"))  
b = nullGrob() # per @baptiste's comment, use nullGrob() instead of rectGrob()

# grid.bezier with a few hard-coded settings
mygb = function(x,y) {
  grid.bezier(x=x, y=y, gp=gpar(fill="black"), 
              arrow=arrow(type="closed", length=unit(2,"mm")))
}

# Create a plot to arrange
p = ggplot(mtcars, aes(wt, mpg)) +
  geom_point()
Run Code Online (Sandbox Code Playgroud)

创建主要情节安排.使用b我们在上面创建的空grob 来分隔图:

grid.arrange(arrangeGrob(p, b, p, p, heights=c(0.3,0.1,0.3,0.3)),
             b,
             arrangeGrob(b, p, p, b, p, heights=c(0.07,0.3, 0.3, 0.03, 0.3)),
             ncol=3, widths=c(0.45,0.1,0.45))
Run Code Online (Sandbox Code Playgroud)

添加箭头:

# Switch to viewport for first set of arrows
vp = viewport(x = 0.5, y=.75, width=0.09, height=0.4)
pushViewport(vp)

#grid.rect(gp=gpar(fill="black", alpha=0.1)) # Use this to see where your viewport is located on the full graph layout

# Add top set of arrows
mygb(x=c(0,0.8,0.8,1), y=c(1,0.8,0.6,0.6))
mygb(x=c(0,0.6,0.6,1), y=c(1,0.4,0,0))

# Up to "main" viewport (the "full" canvas of the main layout)
popViewport()

# New viewport for lower set of arrows
vp = viewport(x = 0.6, y=0.38, width=0.15, height=0.3, just=c("right","top"))
pushViewport(vp)

#grid.rect(gp=gpar(fill="black", alpha=0.1))  # Use this to see where your viewport is located on the full graph layout

# Add bottom set of arrows
mygb(x=c(1,0.8,0.8,0), y=c(1,0.9,0.9,0.9))
mygb(x=c(1,0.7,0.4,0), y=c(1,0.8,0.4,0.4))
Run Code Online (Sandbox Code Playgroud)

这是由此产生的情节:

在此输入图像描述