如何在 R 中使用 plot_grid() 函数绘制多个 seqplots(TraMineR 包)?

How to plot several seqplots (TraMineR package) using plot_grid() function in R?

我正在尝试使用 plot_grid() 函数绘制使用 TraMineR 包创建的 "state sequence object" 的几个图。我的主要问题是,我无法将使用 seqplot() 函数创建的图存储在列表中。我的问题不是关于 ,而是关于如何在网格中实际绘制 seqplots。

我将 ggscatter 图存储在一个列表中,并将该列表传递给之前的 plot_grid() 函数 - 所以我相对确定这在一般情况下是有效的。我觉得问题主要出在seqplot()产生的对象类型上。我尝试使用 as.ggplot() 函数存储绘图,但它不起作用(下面的示例 A)。

使用recordPlot()函数或多或少会起作用。虽然看起来不太好(下面的示例 B + C)。

library(TraMineR)
library(ggplotify)

data(biofam)
biofam.lab <- c("Parent", "Left", "Married", "Left+Marr",
                "Child", "Left+Child", "Left+Marr+Child", "Divorced")
biofam.seq <- seqdef(biofam[1:600,], 10:25, labels=biofam.lab)

# Example A ---------------------------------------------------------------

# not even able to store the plot
plot.list <- list()
plot.list[[1]] <- as.ggplot(seqplot(biofam.seq, type = "I", with.legend = FALSE, sortv = "from.start"))

# Example B and C ---------------------------------------------------------

plot.list <- list()
seqplot(biofam.seq, type = "I", with.legend = FALSE, sortv = "from.start")
plot.list[[1]] <- recordPlot()
seqplot(biofam.seq, type = "I", with.legend = FALSE, sortv = "from.start")
plot.list[[2]] <- recordPlot()
seqplot(biofam.seq, type = "I", with.legend = FALSE, sortv = "from.start")
plot.list[[3]] <- recordPlot()
seqplot(biofam.seq, type = "I", with.legend = FALSE, sortv = "from.start")
plot.list[[4]] <- recordPlot()

# Example B

plot_grid(plotlist = plot.list, ncol = 2)

# Example C

plot_grid(
  plot_grid(plotlist = plot.list, ncol = 2),
  plot_grid(plotlist = plot.list, ncol = 2)
)

我想相对自由地定位要在网格中绘制的实际元素。例如,我想在 5 x 3 网格中保存一个包含 13 个这样的图和一个图例的页面 - 如示例所示。这就是为什么我认为 plot_grid() 比 par(mfrow = c(5,3)) 更有效。此外,使用 par() 我得到 "Error in plot.new() : figure margins too large".

seqplot 内部使用基数 plot。因此,使用 layout 绘制多个图形会更好。您只需制作一个布局矩阵并绘制一个接一个的图。图例 seqlegend 也可以看作是一个情节。这是一个包含您的数据的示例和四个带有图例的图。

layout(matrix(c(1, 2, 2, 3:5), ncol=3, byrow=TRUE))
layout.show(5)  # this line is just to get the preview below where the plots will be placed

seqplot(biofam.seq, type="I", with.legend=FALSE, sortv="from.start")
seqlegend(biofam.seq, cex=.9, ncol=5, position="bottom")  # legend
seqplot(biofam.seq, type="I", with.legend=FALSE, sortv="from.start")
seqplot(biofam.seq, type="I", with.legend=FALSE, sortv="from.start")
seqplot(biofam.seq, type="I", with.legend=FALSE, sortv="from.start")

产量

当然,要获得正确的尺寸,请使用例如pdfpng 设备,在 this answer.

中有很好的解释