微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

sf:使用 ggplot2 输出对象创建 GeoPDF

如何解决sf:使用 ggplot2 输出对象创建 GeoPDF

我尝试使用在 ggplot 中创建的地图保存为 *pdf,以便使用函数 sf::st_write() 创建地理配准 pdf,但没有成功。在我的例子中:

#Packages
library(ggplot2)
library(ggspatial)
library(sf)

# Get data set - x any are the points
all.stands.predict<-read.csv("https://raw.githubusercontent.com/Leprechault/trash/main/prediction__bug_2021-03-18.csv")
all.stands.predict<-all.stands.predict[all.stands.predict[,3]=="VILA PALMA",] # Area selection

#Create a map
(sites <- st_as_sf(all.stands.predict,coords = c("x","y"),crs = 4326,agr = "constant"))
gg <- ggplot() +
  geom_sf(data=sites,color="red") +
  annotation_north_arrow(location = "bl",which_north = "true",pad_x = unit(0.3,"in"),pad_y = unit(0.5,style = north_arrow_fancy_orienteering) + #Add a north arrow
  annotation_scale(location = "bl",width_hint = 0.55) + #Add a scale bar
  xlab("Longitude") + ylab("Latitude") +
  theme_bw() 

# I inspected the map created
plot(gg)

mymap

#Save map as GeoPDF 
st_write(gg,"mymap.pdf",driver = "pdf")

显然输出是:

Error in UseMethod("st_as_sf") : 
method not applicable for 'st_as_sf' applied to a class object "c('gg','ggplot')" 

任何将 ggplot 对象转换为 sf 对象的方法也不起作用。我还没有尝试使用 RQGISRSAGA 之类的软件包。

请问,有什么方法可以使用 sf 轻松创建 GeoPDF 地图吗?

解决方法

解决方案有两个步骤。首先,您在栅格中转换 ggplot2 对象,然后使用 myGeoTiffgg.tif 包中的 myGeoTiffgg.pdf 将创建的栅格 (gdal_translate) 转换为 geoPDF (gdalUtils)。>

# Save the plot
ggsave(plot=gg,"gg.tiff",device = "tiff",dpi = 600)

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

# Get the GeoSpatial Components
lat_long <- ggplot_build(gg)$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,"myGeoTiffgg.tif",options="PHOTOMETRIC=RGB",datatype="INT1U",overwrite=TRUE)

#Save raster as GeoPDF
gdalUtils::gdal_translate("myGeoTiffgg.tif","myGeoTiffgg.pdf",of="PDF",ot="Byte",co="TILED=YES",verbose=TRUE,overwrite=T,a_srs="+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0")
}
#

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。