问题描述
我有一堆代码,这些代码循环遍历一堆数据以产生一系列汇总指标.我还想生成一系列图,然后将其放入循环外的选择网格中.在R中可以吗?
I have a bunch of code that loops through a heap of data to produce a series of summary metrics. I also want to generate a series of plots that I can then put into a grid of my choosing outside the loop. Is this possible in R?
这是我的意思的一个非常简单的例子
Here's a very simple example of what I mean
it = 0
while (it < 5){
myX = runif(10)
myY = runif(10)
df = data.frame(x,y)
plt[it] = ggplot(data = df, aes(myX, myY)) + geom_point(size = 2, color = "blue")
it = it + 1
}
然后我想将plt组织成一个网格
I then want to organise the plt into a grid
(尽管这似乎不产生图表,但不确定为什么)
(although this does not seem to produce the plots, not sure why)
然后,我可以通过调用plt [2]或其他任何东西来显示每个图,将它们放置在网格中,进行组织等.我是ggplot的新手,并且只有基本的R用户,因此如果我不了解明显的内容,深表歉意.甚至不确定使用哪种语言进行搜索.
I would then be able to display each of the plots, put them in a grid, organise them etc. by calling the plt[2] or whatever. I'm very new to ggplot and only a basic R user, so apologies if I'm missing the obvious. Not even sure what language to use to search for this.
也很高兴得知这是一个不好的方法,并且有更好的方法来创建情节.我想在循环外进行操作,因为我想在决定如何排列结果之前先检查一下结果.
Also happy to be told this is a bad approach and there's a better way to create the plots. I want to do it outside the loop as I want to examine the results before deciding how to arrange them.
推荐答案
您可以将结果存储在列表中.要更正 while
循环,您可以执行以下操作:
You could store the results in a list. To correct your while
loop you can do :
library(ggplot2)
plt <- vector('list', 4)
it = 1
while (it < 5){
myX = runif(10)
myY = runif(10)
df = data.frame(myX,myY)
plt[[it]] = ggplot(data = df, aes(myX, myY)) +
geom_point(size = 2, color = "blue")
it = it + 1
}
另一种方法是编写一个函数,并使用 replicate
对其调用 n
次.
create_plot <- function() {
myX = runif(10)
myY = runif(10)
df = data.frame(myX,myY)
ggplot(data = df, aes(myX, myY)) + geom_point(size = 2, color = "blue")
}
plt <- replicate(4, create_plot(), simplify = FALSE)
您可以使用 plt [[1]]
, plt [[2]]
等访问单个图.
You could access individual plots with plt[[1]]
, plt[[2]]
and so on.
这篇关于设置并保存ggplots以便以后显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!