我想在一页上创建多个绘图,在同一 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)
最佳答案
我提出了另一个基于this post的解决方案.
Plotfunction <- function(y){my.plot <-
ggplot(df, aes_string(x = "x",
y = y,
group = "group",
color = "group")) +
geom_line()}
n <- ceiling(sqrt(length(my.s)))
do.call("grid.arrange",
c(lapply(my.s, Plotfunction), ncol = n, nrow = n))
关于R::ggplot2 循环 Y 向量以在一页上绘制多个图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62799928/