r - sf:使用 ggplot2 输出对象创建 GeoPDF
问题描述
我尝试使用创建的地图ggplot
另存为*pdf
,以便使用该功能创建地理配准pdf,sf::st_write()
但没有成功。在我的例子中:
#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, "in"),
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)
#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
都不起作用。我还没有尝试使用类似RQGIS
or的包RSAGA
。
拜托,有一些方法可以使用?轻松创建 GeoPDF 地图sf
?
解决方案
解决方案有两个步骤。首先,您转换ggplot2
光栅中的对象,然后将创建的光栅 ( myGeoTiffgg.tif
) 转换为 geoPDF ( myGeoTiffgg.pdf
),使用包gdal_translate
中的。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,0")
}
#
推荐阅读
- php - 如果另一个表中存在重复项,则更改自动增量值
- python - 如何使用 lxml 正确格式化 xml 文件?
- java - 如何将 Guardian API 添加到依赖项
- python - LinkedIn 自动“登录”点击 Python+Selenium
- c# - 在变量中存储 2^256 个大整数值
- r - 如何解析多个列表的列表并将其转换为 R 中的数据框?
- spring - 在 Spring Security 中从托管 bean 调度到 j_spring_security_check 的问题?
- c# - C# 中带有 SetWindowTextW 的俄语字符
- python - unpickled byte 数组的文件写入默认没有设置权限
- java - 如何解决错误“数据截断:第 1 行的列 'id_brand' 的值超出范围”?