【问题标题】:How to create a For loop with spplot in R?如何在 R 中使用 spplot 创建 For 循环?
【发布时间】:2019-01-20 02:57:13
【问题描述】:

我有带有采样位置和各种变量的空间数据框。我想为 For 循环中的每个变量创建一个空间图。我为此使用了 spplot,当我删除循环时,它适用于单个变量。 我在下面简要描述了数据库和到目前为止我所做的循环。如何构造 For 循环,以便为每个变量生成单独的图?

class       : SpatialPointsDataFrame 
features    : 47 
extent      : -96.57795, -96.56407, 39.10135, 39.10672  (xmin, xmax, ymin, ymax)
coord. ref. : +init=epsg:4269 +proj=longlat +datum=NAD83 +no_defs +ellps=GRS80 +towgs84=0,0,0 
variables   : 18
names       :    Sample_id,         x,        y, bulk_density, Percentage_SOM, Clay, Silt, Very_fine_sand, fine_sand, medium_sand, stone,      Composite_depth, percentage_water, percentage_roots, Percentage_SOM_20cm, ... 
min values  : KLTER/K20A-1, -96.56407, 39.10135,        550.7,            6.9,  3.9, 66.9,            7.4,       0.0,         0.0,   0.1,             7.3,             16.8,             0.10,              4.2315, ... 
max values  : KLTER/K20A-9, -96.57795, 39.10672,       1031.8,           15.1,  8.5, 85.8,           18.5,       9.0,         5.2,  13.7,            20.0,             30.2,             2.16,             11.2000, ... 

df <- K20A_sp3
for(i in names(df))
{ 
  if(is.numeric(df[3,i])) 
    {
    spplot(df, names(zcol= i),
       scales=list(draw=T),
       cex = 1.4, 
       main="Watershed K20A",
       col.regions=brewer.pal(6, "Oranges"))
       dev.off()
     } 
  } 

循环制作.png文件

 for(i in names(df))
     { 
      if(is.numeric(df[3,i])) 
{
  dev.new()
  mypath  <- file.path("C:", "Users", "Ilona", "Documents", "A master thesis", "7.Rstudio", paste("Point_K20A_", i, ".png", sep=""))
  png(file=mypath)
  print(spplot(df, names(zcol= i),
         scales=list(draw=T),
         cex = 1.4, 
         main= paste("Watershed K20A_", i, sep = ""),
         col.regions=brewer.pal(6, "Oranges")
         sp.layout(K20A_DEM))))
  dev.off()
} 

}

【问题讨论】:

  • 你在哪里打开图形设备?看看R FAQ 7.22
  • 我尝试了多种方法;因此, dev.off() 仍然在我的代码中。我不知道它在做什么。我也尝试了打印功能,但我认为我使用不正确或其他什么。我像 print(spplot())、j= spplot()、print(j, i, "/n") 和 print(j) 一样使用它。我仍然不知道如何让它正常工作。
  • dev.off() 关闭打开的图形设备(参见例如 ?png?pdf)。您是否收到如下错误:Error in dev.off() : cannot shut down device 1 (the null device)
  • 感谢您的回复。我没有收到任何错误。这也是一种工作,但我没有得到任何情节。我试图从中制作.png,但也没有制作。
  • 您可以选择将数据转换为data.frame 并使用ggplot2 绘制它们。要将空间对象转换为data.frame,您可以使用fortify。之后,可以使用 facetting 绘制多个变量。

标签: r for-loop sp


【解决方案1】:

您现在可能已经找到了这个问题的答案,但是添加了来自等效 question 的答案。

底线是在循环中需要“打印”绘图:

for(i in 1:10) {
    png(...)
    print(spplot(...))
    dev.off()
}

【讨论】:

    猜你喜欢
    • 2016-07-11
    • 1970-01-01
    • 2021-01-10
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-28
    相关资源
    最近更新 更多