You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将ggplot地图转为地理参考PDF时出现镜像问题

解决ggplot导出GeoPDF镜像问题

问题背景

尝试将ggplot制作的地图转为地理参考PDF用于野外平板设备,操作后导出的GeoPDF呈现镜像效果。切换CRS为4326(WGS84)、调整范围参数顺序、修改GeoTIFF数据类型后问题仍存在,仅在导出GeoTIFF后出现镜像,怀疑北美数据的负经度(及3857下的负X值)是诱因。

核心原因

图像坐标系与地理坐标系的Y轴方向不一致:ggplot输出的图像Y轴从上到下递增,而地理坐标系的Y轴(纬度)从下到上递增,赋值空间范围后直接导致垂直镜像。

解决步骤

  • 给栅格赋值空间范围后,用flip()函数垂直翻转栅格,修正Y轴方向
  • 确保导出GeoTIFF和GeoPDF时的投影参数统一

修改后的完整代码

library(sf)
library(raster)
library(gdalUtilities)
library(tidyverse)

nc <- st_read(system.file("shape/nc.shp", package="sf"),
              quiet=TRUE) %>%
  st_transform(4326)

nc_points <- nc %>%
  st_centroid()


GGPLOT_MAP <- 
  ggplot()+
  geom_sf(
    data = nc,
    inherit.aes = F,
    aes(colour = NAME),
    fill = NA, lwd=1
  ) +
  geom_sf(
    data = nc_points,
    inherit.aes = F,
    aes(colour = as.character(NAME))
  ) +
  geom_sf_text(
    data = nc_points,
    inherit.aes = F,
    aes(label =NAME
    ),size = 1)+
  coord_sf(expand = F )+
  theme(legend.position = "none")

GGPLOT_MAP


ggsave(plot=GGPLOT_MAP, "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(GGPLOT_MAP)$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")

# 关键步骤:垂直翻转栅格,修正Y轴方向
stackedRaster <- flip(stackedRaster, direction = "y")

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

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

内容的提问来源于stack exchange,提问作者BEVAN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 15:47:14