在 R 中将 Path/Route 图写为 GeoTiff

Writing a Path/Route Plot as a GeoTiff in R

我正在使用 geom_path 函数在 R 中绘制一些路线。我希望做的是将我正在绘制的数据转换为 GeoTiff(其中包括用于投影和经纬度角的地理空间组件),我可以将其导入 NASA WorldWind.

我引用的工件可在此处获得:

我做了一个非常简单的例子来说明我有什么,我想做什么:

library(rgdal)
library(ggplot2)
library(png)
library(raster)
library(tiff)


wrld <- readOGR("data" , "ne_110m_admin_0_countries")
base <- ggplot(wrld, aes(x = long, y = lat))


myDataFrame <- data.frame(Name=c("Object1","Object1","Object1","Object2","Object2","Object2"), lat=c(34,30,25,65,32,16), long=c(-118,-120,-114,-63,-108,-110)) 


route <- c(geom_path(aes(long, lat, group = myDataFrame$Name), colour = "#ffff00", size = 2, data =
myDataFrame, alpha = 0.75,
lineend = "round"))


earth <- readTIFF("HYP_LR_SR_W.tif")


pathPlot <- base +  annotation_raster(earth, -180, 180, -90, 90) + route
plot(pathPlot)

产生这个情节的是:

我想做的下一步是将结果图输出为 GeoTIFF(我可以将其导入 WorldWind)。

我想一旦有了堆叠栅格,我就知道以我想要的格式创建 GeoTIFF 的命令,但我无法弄清楚如何将它们连接在一起以从路由到仅包含的 GeoTIFF图像本身,包括地理空间组件:

ggsave(plot=pathPlot, "pathPlot.tiff", device = "tiff")
stackedRaster <- stack("pathPlot.tiff")
xRange <- ggplot_build(pathPlot)$layout$panel_params[[1]][c("x.range")] 
yRange <- ggplot_build(pathPlot)$layout$panel_params[[1]][c("y.range")]     
extent(stackedRaster) <- extent(xRange$x.range[1],xRange$x.range[2], yRange$y.range[1],yRange$y.range[2]) 
projection(stackedRaster) <- CRS("+proj=longlat +datum=WGS84") 
writeRaster(stackedRaster, "myGeoTiff.tiff", options="PHOTOMETRIC=RGB", datatype="INT1U", overwrite=TRUE) 

我认为没有直接的方法可以将 ggplot 对象(即 ggproto)强制转换为 RasterStack 对象。我不确定以下解决方案是否能满足您的要求,但您可以将其视为解决方法:

  1. 使用 ggsave
  2. ggplot 图保存到 tiff 图像中
  3. 使用 stack
  4. 为保存的图像创建一个 RasterStack 对象
  5. 使用 writeRaster
  6. RasterStack 对象保存为 GeoTiff 图像

以上步骤的实现如下:

# This is your pathPlot
pathPlot <- base +  annotation_raster(earth, -180, 180, -90, 90) + route

# Remove the margins from the plot (i.e., keep the earth raster and the routes only)
pathPlot <- pathPlot + 
  theme(    
        axis.ticks=element_blank(), 
        axis.text.x=element_blank(), 
        axis.text.y=element_blank(), 
        axis.title.x=element_blank(), 
        axis.title.y=element_blank(),
        plot.margin = unit(c(0, 0, 0, 0), "null"),
        legend.position = 'none'
       ) +
       labs(x=NULL, y=NULL)

# Save the plot
ggsave(plot=pathPlot, "pathPlot.tiff", device = "tiff")

# Create a StackedRaster object from the saved plot
stackedRaster <- stack("pathPlot.tiff")

# Get the GeoSpatial Components
lat_long <- ggplot_build(pathPlot)$layout$panel_params[[1]][c("x.range","y.range")] 

# Supply GeoSpatial  data to the StackedRaster 
extent(stackedRaster) <- c(lat_long$x.range,lat_long$y.range)
projection(stackedRaster) <- CRS("+proj=longlat +datum=WGS84")

# Create the GeoTiff
writeRaster(stackedRaster, "myGeoTiff.tif", options="PHOTOMETRIC=RGB", datatype="INT1U")

这是生成的 GeoTiff 图像:

希望对你有帮助。