You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

正射投影放大自定义范围时网格线消失,如何调整范围不干扰坐标系?

问题解决:正射投影放大后网格线缺失的处理

你遇到的问题本质是coord_map()的裁剪逻辑导致的:它会先根据经纬度范围裁剪数据和网格线,再进行投影。而正射投影下,部分原本在可视范围内的网格线,其经纬度坐标可能超出了你设置的xlim/ylim,因此被提前裁剪掉,最终显示缺失。

以下是两种可行的解决方法:


方法1:使用coord_sf()替代coord_map()

coord_sf()是ggplot2中处理空间数据的新接口,支持更精准的投影逻辑(先投影再裁剪),能避免网格线被误删。步骤如下:

  1. 加载必要包并获取空间格式的世界地图:
library(ggplot2)
library(sf)
library(rnaturalearth)

# 获取sf格式的世界地图数据
worldmap_sf <- ne_countries(scale = "medium", returnclass = "sf")
  1. 绘制放大的正射投影图:
map_zoom_sf <- ggplot() +
  geom_sf(data = worldmap_sf, fill = "darkgrey") +
  # 设置正射投影(北极点为中心)
  coord_sf(
    crs = "+proj=ortho +lat_0=90 +lon_0=0",
    xlim = c(-50, 120),
    ylim = c(0, 90),
    expand = FALSE
  ) +
  scale_x_continuous(breaks = c(-6:6)*30) +
  scale_y_continuous(breaks = c(-6:6)*15)

map_zoom_sf

方法2:手动生成并添加网格线

如果需要更灵活的网格线控制,可以手动生成经纬度网格线,再投影后添加到图中,完全避开默认网格线的裁剪问题:

library(ggplot2)
library(sf)
library(rnaturalearth)

worldmap_sf <- ne_countries(scale = "medium", returnclass = "sf")

# 生成经纬度网格线的sf数据
# 经度线
lon_lines <- lapply(c(-6:6)*30, function(lon) {
  st_linestring(matrix(c(rep(lon, 13), c(-6:6)*15), ncol = 2))
}) %>% st_sfc(crs = 4326) %>% st_sf()

# 纬度线
lat_lines <- lapply(c(-6:6)*15, function(lat) {
  st_linestring(matrix(c(c(-6:6)*30, rep(lat, 13)), ncol = 2))
}) %>% st_sfc(crs = 4326) %>% st_sf()

# 绘图
map_zoom_custom <- ggplot() +
  geom_sf(data = worldmap_sf, fill = "darkgrey") +
  # 添加自定义网格线
  geom_sf(data = lon_lines, color = "grey", linetype = "dashed") +
  geom_sf(data = lat_lines, color = "grey", linetype = "dashed") +
  coord_sf(
    crs = "+proj=ortho +lat_0=90 +lon_0=0",
    xlim = c(-50, 120),
    ylim = c(0, 90),
    expand = FALSE
  ) +
  # 关闭默认网格线
  theme(panel.grid = element_blank())

map_zoom_custom

这两种方法都能在调整绘图范围的同时,完整显示所有应该出现在可视区域内的网格线。

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

火山引擎 最新活动