【问题标题】:Creating and saving same plot for multiple data files - only saving image for 1 file and this is appearing as a white rectangle with no data为多个数据文件创建和保存相同的图 - 仅保存 1 个文件的图像,这显示为没有数据的白色矩形
【发布时间】: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()'

标签: r for-loop ggplot2


【解决方案1】:

我想提供一个替代策略

  1. 输入文件路径

    filepath <- dir(path=".", pattern="csv", full.names=TRUE)

  2. 使用正则表达式编辑文件名。例如,替换“.csv”扩展名 和/或喜欢字符串文字和插值(参见library(glue))。 在现实生活中的大多数时候,我不想将上面full.names 选项生成的整个路径发扬光大。

OUTPATH &lt;- "whatever/Rplot"

filenames &lt;- paste0(OUTPATH, gsub("\\.csv$", ".png", filepath))

编辑您的makeplot() 签名,如下所示:

makeplot &lt;- function(filepath, filenames) {

然后移动到更惯用的Map() 来迭代两个列表 注意:请随时从purrr 签出map2 作为Map() 的替代品

Map(function(x, y) makeplot(filepath = x, filenames = y), 
     x = filepath, 
     y = filenames)

【讨论】:

    猜你喜欢
    • 2021-12-10
    • 2017-12-31
    • 2022-01-03
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多