【发布时间】:2018-11-15 16:12:14
【问题描述】:
我准备了一个建模程序,它生成 26 个单独的文件,我需要在 R 中以相同的方式绘制等高线图 - 我计划重复运行该程序,因此一直在尝试创建一个循环来创建和保存图每次运行的所有 26 个文件。
我正在尝试使用它们的原始文件名保存文件(现在已经放置了一个占位符名称),因此我创建了对象“名称”并将每个文件保存到 png 或 jpeg 文件中。目前,循环仅保存 1 个文件(尽管使用 list.files 读取 4 组数据),并且这显示为具有正确尺寸的白色方块,而不是由“makeplot”生成的图形(已在单个文件上进行测试) )。
我的数据样本:
Z X T
0 0 0
0 0.005 0
0 0.01 0
0 0.015 0
(对于 84k 行,依此类推)
我的代码:
filenames <- list.files(path=".",
pattern="csv",
full.names=TRUE)
names <- as.vector(filenames)
# Creating a directory to save contour plots
dir.create("Contour plots")
#Creates a contour plot in ggplot of the variable in xz space
makeplot <- function(filename) {
data <- as.data.frame(read.csv(file = filename), header = FALSE)
ggplot(data=data, mapping = aes(x = data[,2],
y=data[,1],
z = data[,3])) +
geom_raster(data=data, aes(fill=data[,3]), show.legend=TRUE, interpolate
= FALSE) +
scale_fill_gradient(limits=range(data[,3]), high = 'red', low =
'white')+
geom_contour(bins = 30, colour = "black") +
xlab(label = "Distance from ridge axis") +
ylab(label = "Depth") +
theme_classic()+
coord_cartesian(
ylim = c(0,1), xlim = c(0,2))+
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
guides(fill=guide_legend(title="Yb concentration")) +
theme(legend.position="bottom")
}
for (f in filenames) {
png(filename="Rplot%03d.png", height = 600, width = 1200)
makeplot(f)
dev.off()
}
任何帮助将不胜感激!
【问题讨论】:
-
我认为您只需将
png(..)和dev.off()放在for循环的外部 就可以了。 -
您好 Milan,感谢您回复我 - 这似乎仍然无法正常工作,我只能假设我的 for 循环中的语法有问题?
-
嗨,试试
print(makeplot(f))在循环中? -
这是我的一个旧答案,与您尝试做的非常相似,并且完全可重现。 stackoverflow.com/questions/26034177/…
-
谢谢!我最终使用 print 并更改了我对循环的调用:'pdf(file = pdfmaster [1],height = 6,width = 12)for(f in 1:length(filenames)){print( makeplot(filenames[f])) } dev.off()'