【发布时间】:2020-07-08 17:05:02
【问题描述】:
我想在一页上创建多个图,我在同一个 X 上对不同的 Y 变量进行迭代。= 即我希望每个 Y 一个图。通常,我会复制并粘贴我的 ggplot更改 Y 值,将单个图存储为 p.y1, p.y2 并使用 grid.arrange(p.y1, p.y2) 绘制所有图,如下所示:
当我有 10 个不同的 Y 变量并且我想绘制所有这些变量时,这种方法不是很有趣。我想知道如何让这个过程更有效率?
我认为我可以简单地创建一个 Y 向量(df 的列名),然后遍历它们以创建多个图。但是,我的输出图似乎不正确传递给grid.arrange(),我也无法绘制它们。
如何循环遍历多个 Y,然后将所有绘图排列在一页上?由于我没有多重因素,我可能无法使用facet_grid 或facet_wrap。
这是我的两个 Y 的虚拟示例:y1 和 y2
set.seed(5)
df <- data.frame(x = rep(c(1:5), 2),
y1 = rnorm(10)*3+2,
y2 = rnorm(10),
group = rep(c("a", "b"), each = 5))
# Example of simple line ggplot
ggplot(df, aes(x = x,
y = y2, # here I can set either y1, y2...
group = group,
color = group)) +
geom_line()
现在,遍历 Ys 的向量并将输出图存储在列表中:
# create vector of my Ys
my.s<-c("y1", "y2")
# Loop over list of y to create different plots
outPlots<- list()
for (i in my.s) {
print(i)
my.plot <-
ggplot(df, aes_string(x = "x",
y = i,
group = "group",
color = "group")) +
geom_line()
# print(plot)
outPlots <- append(outPlots, my.plot)
}
在一页上绘制多个图表:由于Error in gList(list(data.x1 = 1L, data.x2 = 2L, data.x3 = 3L, data.x4 = 4L, : only 'grobs' allowed in "gList"而不起作用
grid.arrange(outPlots)
【问题讨论】: