R语言地理信息系统地图绘制实战技巧与常见问题解析

引言:R语言在GIS地图绘制中的重要性
地理信息系统(GIS)地图绘制是数据分析和空间可视化的重要组成部分。R语言凭借其强大的数据处理能力和丰富的包生态系统,已成为GIS专业人士和数据科学家的首选工具之一。与传统的GIS软件相比,R语言提供了更灵活的数据操作方式、更强大的统计分析能力以及更便捷的自动化流程。
在R语言的GIS生态系统中,
sf
、
sp
、
raster
、
ggplot2
和
leaflet
等包构成了核心工具集。这些包不仅支持从简单的点线面绘制到复杂的栅格数据可视化,还能处理从本地静态地图到交互式网络地图的各种需求。本文将系统地介绍R语言GIS地图绘制的实战技巧,并深入解析常见问题,帮助读者掌握高效、专业的地图制作方法。
1. R语言GIS地图绘制基础
1.1 空间数据基础概念
在开始绘制地图之前,理解空间数据的基本概念至关重要。空间数据主要分为矢量数据和栅格数据两种类型:
矢量数据
:由点、线、面等几何对象组成,适合表示离散的地理要素(如城市、道路、行政区划)。常见的矢量数据格式包括Shapefile(.shp)、GeoJSON等。
栅格数据
:由规则的网格单元组成,每个单元存储一个值,适合表示连续的地理现象(如高程、温度、降水)。常见的栅格数据格式包括GeoTIFF、ASCII Grid等。
坐标参考系统(CRS)是空间数据的核心属性,它定义了数据在地球表面的位置。常见的CRS包括:
WGS84(EPSG:4326):全球通用的经纬度坐标系
Web Mercator(EPSG:3857):网络地图常用投影
UTM(通用横轴墨卡托投影):适合区域地图的投影
1.2 核心包安装与加载
R语言GIS地图绘制主要依赖以下包:
# 安装必要的包
install.packages(c(“sf”, “sp”, “raster”, “ggplot2”, “leaflet”,
“rnaturalearth”, “rnaturalearthdata”, “dplyr”))

# 加载包
library(sf) # 简单特征对象处理
library(sp) # 旧版空间对象处理
library(raster) # 栅格数据处理
library(ggplot2) # 数据可视化
library(leaflet) # 交互式地图
library(dplyr) # 数据处理
library(rnaturalearth) # 自然地球数据
1.3 数据读取与准备
R语言可以读取多种空间数据格式。以下是读取Shapefile和GeoJSON的示例:
# 读取Shapefile
# 注意:文件路径需要根据实际情况修改
# shapefile_path <- "path/to/your/file.shp" # data_sf <- st_read(shapefile_path) # 读取GeoJSON # geojson_path <- "path/to/your/file.geojson" # data_sf <- st_read(geojson_path) # 使用rnaturalearth包获取世界地图数据 world <- ne_countries(scale = "medium", returnclass = "sf") class(world) # 查看对象类型 1.4 坐标参考系统(CRS)操作 CRS是空间数据处理的核心,正确设置和转换CRS是成功绘图的关键: # 查看当前CRS st_crs(world) # 转换CRS(例如转换为Web Mercator) world_mercator <- st_transform(world, crs = 3857) # 设置CRS(当数据没有CRS信息时) # world <- st_set_crs(world, 4326) # 检查CRS是否正确 if (is.na(st_crs(world))) { warning("数据缺少CRS信息!") } 2. 静态地图绘制技巧 2.1 基于ggplot2的静态地图绘制 ggplot2 是R语言中最强大的可视化包,结合 geom_sf() 函数可以轻松绘制专业地图: # 基础世界地图 ggplot(data = world) + geom_sf(aes(fill = pop_est), color = "white", size = 0.2) + scale_fill_viridis_c(option = "plasma", name = "人口数量") + labs(title = "世界人口分布图", subtitle = "数据来源:Natural Earth", caption = "R语言GIS地图绘制示例") + theme_minimal() + theme(legend.position = "bottom") 2.2 添加地图元素 专业地图需要包含标题、比例尺、指北针等元素: # 添加地图元素 library(ggsn) # 用于添加比例尺和指北针 # 绘制基础地图 base_map <- ggplot(data = world) + geom_sf(aes(fill = pop_est), color = "white", size = 0.2) + scale_fill_viridis_c(option = "plasma", name = "人口数量") + labs(title = "世界人口分布图") + theme_minimal() # 添加比例尺和指北针(需要指定地图边界) # 注意:ggsn包需要地图投影信息,这里仅作示例 # base_map + # north(world, location = "topright") + # scalebar(world, dist = 1000, transform = TRUE, model = "WGS84") 2.3 多图层叠加与组合 复杂地图通常需要叠加多个图层,如行政区划、道路、POI点等: # 生成示例数据:中国主要城市 china_cities <- data.frame( name = c("北京", "上海", "广州", "深圳", "成都"), lon = c(116.4074, 121.4737, 113.2644, 114.0579, 104.0668), lat = c(39.9042, 31.2304, 23.1291, 22.5431, 30.5728), population = c(2154, 2424, 1868, 1756, 2094) # 万人口 ) # 转换为sf对象 china_cities_sf <- st_as_sf(china_cities, coords = c("lon", "lat"), crs = 4326) # 绘制多图层地图 ggplot() + geom_sf(data = world, fill = "lightgray", color = "white", size = 0.1) + geom_sf(data = china_cities_sf, aes(size = population, color = name), alpha = 0.7) + geom_text(data = china_cities, aes(x = lon, y = lat, label = name), size = 3, hjust = -0.1, vjust = 0.5) + scale_size_continuous(range = c(2, 8), name = "人口(万)") + scale_color_brewer(palette = "Set1", name = "城市") + coord_sf(xlim = c(70, 140), ylim = c(15, 55)) + # 限制中国区域 labs(title = "中国主要城市分布图") + theme_minimal() + theme(legend.position = "right") 2.4 分面地图(Facet Maps) 分面地图可以展示不同时间或不同变量的空间分布: # 创建示例数据:不同年份的GDP数据 set.seed(123) years <- 2018:2020 gdp_data <- expand.grid(year = years, region = c("East", "West", "North", "South")) gdp_data$gdp <- round(runif(nrow(gdp_data), 1000, 5000)) gdp_data$lon <- gdp_data$region gdp_data$lon <- ifelse(gdp_data$region == "East", 120, ifelse(gdp_data$region == "West", 100, ifelse(gdp_data$region == "North", 116, 112))) gdp_data$lat <- ifelse(gdp_data$region == "East", 31, ifelse(gdp_data$region == "West", 30, ifelse(gdp_data$region == "North", 40, 23))) # 转换为sf对象 gdp_sf <- st_as_sf(gdp_data, coords = c("lon", "lat"), crs = 4326) # 分面地图 ggplot(data = gdp_sf) + geom_sf(data = world, fill = "lightgray", color = "white", size = 0.1) + geom_sf(aes(size = gdp, color = region), alpha = 0.8) + facet_wrap(~year, ncol = 2) + scale_size_continuous(range = c(2, 10), name = "GDP(亿元)") + scale_color_brewer(palette = "Set1", name = "区域") + labs(title = "不同年份各区域GDP分布") + theme_minimal() + theme(legend.position = "bottom") 3. 交互式地图绘制技巧 3.1 Leaflet基础应用 Leaflet是R语言中最流行的交互式地图包,支持多种底图和图层控制: # 基础Leaflet地图 leaflet() %>%
addTiles() %>% # 添加默认OpenStreetMap底图
setView(lng = 116.4074, lat = 39.9042, zoom = 5) # 设置初始视图

# 添加中国城市标记
leaflet(data = china_cities_sf) %>%
addTiles() %>%
addCircleMarkers(
radius = ~sqrt(population)/5,
color = “blue”,
fillOpacity = 0.7,
popup = ~paste(name, “人口:”, population, “万”)
) %>%
addLegend(
“bottomright”,
colors = c(“blue”),
labels = c(“城市”),
title = “图例”
)
3.2 多图层控制与底图切换
专业交互地图需要支持多图层控制和底图切换:
# 创建多图层交互地图
leaflet(data = world) %>%
addProviderTiles(“CartoDB.Positron”) %>% # 添加专业底图
addPolygons(
fillColor = ~colorNumeric(“YlOrRd”, pop_est)(pop_est),
weight = 1,
color = “white”,
fillOpacity = 0.7,
highlightOptions = highlightOptions(
weight = 3,
color = “#666”,
fillOpacity = 0.9,
bringToFront = TRUE
),
label = ~paste(name, “人口:”, pop_est),
group = “国家边界”
) %>%
addCircleMarkers(
data = china_cities_sf,
radius = ~sqrt(population)/5,
color = “red”,
fillOpacity = 0.8,
popup = ~paste(name, “人口:”, population, “万”),
group = “中国城市”
) %>%
addLayersControl(
baseGroups = c(“CartoDB.Positron”, “OpenStreetMap”, “Esri.WorldImagery”),
overlayGroups = c(“国家边界”, “中国城市”),
options = layersControlOptions(collapsed = FALSE)
) %>landmark
addLegend(
“bottomright”,
pal = colorNumeric(“YlOrRd”, world$pop_est),
values = ~pop_est,
title = “人口数量”,
opacity = 0.7
)
3.3 时间序列交互地图
使用
leaflet
和
shiny
可以创建动态时间序列地图:
library(shiny)
library(leaflet)
library(DT)

# Shiny UI
ui <- fluidPage( titlePanel("动态时间序列地图"), sidebarLayout( sidebarPanel( sliderInput("year", "选择年份", 2018, 2020, 2018), selectInput("region", "选择区域", choices = c("All", "East", "West", "North", "South")) ), mainPanel( leafletOutput("map", height = "500px"), dataTableOutput("table") ) ) ) # Shiny Server server <- function(input, output, session) { # 过滤数据 filtered_data <- reactive({ data <- gdp_data if (input$region != "All") { data <- data[data$region == input$region, ] } data[data$year == input$year, ] }) # 渲染地图 output$map <- renderLeaflet({ data_sf <- st_as_sf(filtered_data(), coords = c("lon", "lat"), crs = 4326) leaflet(data_sf) %>%
addTiles() %>%
addCircleMarkers(
radius = ~sqrt(gdp)/10,
color = ~colorFactor(“Set1”, region)(region),
popup = ~paste(region, “GDP:”, gdp, “亿元”)
)
})

# 渲染表格
output$table <- renderDataTable({ filtered_data() }) } # 运行应用 # shinyApp(ui, server) 4. 栅格数据可视化技巧 4.1 栅格数据基础操作 栅格数据在环境科学、遥感等领域应用广泛。以下是栅格数据的创建和基本操作: # 创建示例栅格数据 r <- raster(ncol = 10, nrow = 10) values(r) <- 1:100 # 设置栅格值 crs(r) <- CRS("+init=epsg:4326") # 设置CRS extent(r) <- c(0, 10, 0, 10) # 设置范围 # 查看栅格信息 print(r) plot(r, main = "基础栅格数据") 4.2 栅格数据可视化 使用 ggplot2 和 rasterVis 包可以创建美观的栅格地图: # 转换为数据框用于ggplot2 r_df <- as.data.frame(r, xy = TRUE) colnames(r_df) <- c("x", "y", "value") # 使用ggplot2绘制栅格 ggplot(data = r_df) + geom_raster(aes(x = x, y = y, fill = value)) + scale_fill_viridis_c(option = "viridis", name = "值") + labs(title = "栅格数据可视化", x = "经度", y = "纬度") + coord_fixed() + theme_minimal() # 使用rasterVis包(更专业的栅格可视化) library(rasterVis) levelplot(r, main = "栅格数据Levelplot", margin = FALSE) 4.3 栅格代数运算与可视化 栅格数据的强大之处在于可以进行像元级别的代数运算: # 创建第二个栅格 r2 <- raster(ncol = 10, nrow = 10) values(r2) <- runif(100, 0, 100) crs(r2) <- CRS("+init=epsg:4326") extent(r2) <- c(0, 10, 0, 10) # 栅格代数运算 r_sum <- r + r2 # 加法 r_diff <- r - r2 # 减法 r_prod <- r * r2 # 乘法 r_mask <- r > 50 # 条件筛选

# 可视化结果
par(mfrow = c(2, 2))
plot(r, main = “栅格1”)
plot(r2, main = “栅格2”)
plot(r_sum, main = “栅格1 + 栅格2”)
plot(r_mask, main = “栅格1 > 50”)
4.4 栅格重采样与重投影
# 重采样到不同分辨率
r_coarse <- aggregate(r, fact = 2, fun = mean) # 降低分辨率 r_fine <- disaggregate(r, fact = 2) # 提高分辨率(插值) # 重投影 r_projected <- projectRaster(r, crs = "+init=epsg:3857", method = "bilinear") # 可视化比较 par(mfrow = c(1, 2)) plot(r, main = "原始投影 (WGS84)") plot(r_projected, main = "重投影 (Web Mercator)") 5. 常见问题解析 5.1 坐标参考系统(CRS)问题 问题1:数据缺少CRS信息 # 问题:数据没有CRS信息 # 解决方案:手动设置CRS world <- st_read("world.shp") if (is.na(st_crs(world))) { world <- st_set_crs(world, 4326) # 假设是WGS84 } 问题2:CRS不匹配导致图层无法叠加 # 问题:两个图层CRS不同,无法正确叠加 # 解决方案:统一CRS layer1 <- st_transform(layer1, st_crs(layer2)) # 或者统一为特定CRS layer1 <- st_transform(layer1, 3857) layer2 <- st包crs(layer2, 3857) 问题3:投影变形问题 # 问题:全球地图使用WGS84投影会出现变形 # 解决方案:使用合适的投影 # 对于全球地图,使用Robinson投影或Winkel Tripel投影 world_robinson <- st_transform(world, crs = "+proj=robin") ggplot(data = world_robinson) + geom_sf() + coord_sf(crs = "+proj=3857") 5.2 数据格式与读取问题 问题1:Shapefile读取失败 # 问题:Shapefile文件不完整(缺少.dbf或.shx文件) # 解决方案:确保所有Shapefile组件文件都存在 # 或者使用其他格式如GeoJSON # 如果必须使用Shapefile,检查文件完整性 files <- list.files("path/to/shapefile", pattern = "\\.shp$|\\.dbf$|\\.shx$|\\.prj$") if (length(files) < 4) { stop("Shapefile文件不完整!") } 问题2:中文路径或中文属性乱码 # 问题:读取中文Shapefile时出现乱码 # 解决方案:指定编码 data <- st_read("path/to/file.shp", options = "ENCODING=UTF-8") # 或者 data <- st_read("path/to/file.shp", options = "ENCODING=GBK") 5.3 内存与性能问题 问题1:大数据量渲染缓慢 # 问题:大数据量地图渲染缓慢 # 解决方案1:简化几何 world_simple <- st_simplify(world, dTolerance = 1000) # 单位取决于CRS # 解决方案2:使用data.table加速数据处理 library(data.table) world_dt <- as.data.table(world) # 解决方案3:分块处理或抽样 world_sample <- world[sample(nrow(world), 100), ] # 抽样100个要素 问题2:内存不足 # 问题:处理大型栅格数据时内存不足 # 解决方案:使用raster包的内存管理功能 r <- raster("large_file.tif") # 使用块处理而不是一次性读取 values_in_memory <- readValues(r, row = 1, nrows = nrow(r)) # 或者使用rasterVis的levelplot进行分块渲染 5.4 可视化与美学问题 问题1:颜色方案选择不当 # 问题:颜色对比度不足或色盲不友好 # 解决方案:使用ColorBrewer或Viridis颜色方案 # 连续变量 ggplot(data = world) + geom_sf(aes(fill = pop_est), color = "white") + scale_fill_viridis_c(option = "plasma", name = "人口") # 色盲友好 # 分类变量 ggplot(data = world) + geom_sf(aes(fill = continent), color = "white") + scale_fill_brewer(palette = "Set2", name = "大洲") # ColorBrewer方案 问题2:图例和标签混乱 # 问题:图例位置不当或标签重叠 # 解决方案:优化图例和标签 ggplot(data = world) + geom_sf(aes(fill = pop_est), color = "white") + scale_fill_viridis_c( option = "plasma", name = "人口数量", breaks = c(0, 1e6, 1e7, 1e8), # 自定义断点 labels = c("0", "100万", "1000万", "1亿") # 自定义标签 ) + labs(title = "世界人口分布", x = "经度", y = "纬度") + theme(legend.position = "bottom", legend.key.width = unit(2, "cm")) 问题3:地图要素不完整 # 问题:缺少比例尺、指北针等专业要素 # 解决方案:使用ggspatial包 library(ggspatial) ggplot(data = world) + geom_sf(fill = "lightgray", color = "white") + annotation_north_arrow(location = "tr", which_north = "true") + annotation_scale(location = "bl", pad_x = unit(0.2, "in"), pad_y = unit(0.2, "in")) + labs(title = "带比例尺和指北针的地图") 5.5 交互式地图常见问题 问题1:Leaflet地图加载缓慢 # 问题:大数据量导致交互卡顿 # 解决方案:简化数据或使用聚类 leaflet(data = world) %>%
addTiles() %>%
addPolygons(
fillColor = ~colorNumeric(“YlOrRd”, pop_est)(pop_est),
weight = 0.5,
color = “white”,
fillOpacity = 0.6,
# 使用聚类
clusterOptions = markerClusterOptions()
)
问题2:弹出窗口(Popup)格式混乱
# 问题:Popup内容格式不美观
# 解决方案:使用HTML格式化
leaflet(data = china_cities_sf) %>%
addTiles() %>%
addCircleMarkers(
popup = ~paste0(
“

“,
“

“, name, “

“,
“

人口: “, population, “万

“,
“

坐标: “, round(st_coordinates(geometry)[1], 2), “,”,
round(st_coordinates(geometry)[2], 2), “

“,
“

”
)
)
6. 高级技巧与最佳实践
6.1 空间分析与地图结合
将空间分析结果直接可视化是R语言的优势:
# 空间连接分析
# 计算每个国家的平均海拔(假设我们有海拔数据)
# 这里用随机数据模拟
world$elevation <- runif(nrow(world), 0, 5000) # 空间聚合:按大洲汇总 continent_summary <- world %>%
group_by(continent) %>%
summarise(
total_pop = sum(pop_est),
mean_elevation = mean(elevation),
count = n()
)

# 可视化聚合结果
ggplot(data = continent_summary) +
geom_sf(aes(fill = mean_elevation), color = “white”) +
scale_fill_viridis_c(option = “magma”, name = “平均海拔(m)”) +
labs(title = “各大陆平均海拔分布”) +
theme_minimal()
6.2 自动化地图生产
使用循环或函数批量生成地图:
# 批量生成各大陆地图
continents <- unique(world$continent) for (cont in continents) { # 过滤数据 cont_data <- world %>% filter(continent == cont)

# 生成地图
p <- ggplot(data = cont_data) + geom_sf(aes(fill = pop_est), color = "white") + scale_fill_viridis_c(option = "plasma") + labs(title = paste(cont, "人口分布")) + theme_minimal() # 保存地图 ggsave(filename = paste0("map_", cont, ".png"), plot = p, width = 10, height = 8, dpi = 300) } 6.3 与外部数据源集成 # 从PostGIS数据库读取数据 library(RPostgreSQL) con <- dbConnect(PostgreSQL(), dbname = "gisdb", host = "localhost", user = "postgres", password = "password") roads <- st_read_db(con, query = "SELECT * FROM roads WHERE city = 'Beijing'") dbDisconnect(con) # 从API获取实时数据 library(httr) library(jsonlite) # 示例:从OpenWeatherMap获取天气数据 # 注意:需要API key # response <- GET("http://api.openweathermap.org/data/2.5/weather?q=Beijing&appid=YOUR_API_KEY") # weather_data <- fromJSON(content(response, "text")) 6.4 地图输出与分享 # 高分辨率输出 ggsave("high_res_map.png", width = 12, height = 8, dpi = 600, bg = "white") # PDF矢量输出(适合印刷) ggsave("vector_map.pdf", width = 12, height = 8, device = cairo_pdf) # 交互式HTML输出 library(htmlwidgets) saveWidget(leaflet_map, "interactive_map.html") # 在R Markdown中嵌入地图 # ```{r} # leaflet(data = world) %>% addTiles()
# “`
7. 总结
R语言为GIS地图绘制提供了强大而灵活的解决方案。通过掌握
sf
、
ggplot2
和
leaflet
等核心包的使用,结合空间分析和数据处理技巧,可以创建从简单静态地图到复杂交互式应用的各种地图产品。
关键要点:
数据准备
:确保空间数据的CRS正确,数据格式兼容
可视化选择
:根据需求选择静态或交互式地图,使用合适的颜色方案
性能优化
:处理大数据时注意简化几何、分块处理
专业性
:添加必要的地图元素(比例尺、指北针、图例)
自动化
:使用函数和循环批量生产地图
通过本文介绍的技巧和问题解决方案,读者可以显著提高R语言GIS地图绘制的效率和质量,制作出专业级别的空间可视化作品。
# R语言地理信息系统地图绘制实战技巧与常见问题解析
引言:R语言在GIS地图绘制中的重要性
地理信息系统(GIS)地图绘制是数据分析和空间可视化的重要组成部分。R语言凭借其强大的数据处理能力和丰富的包生态系统,已成为GIS专业人士和数据科学家的首选工具之一。与传统的GIS软件相比,R语言提供了更灵活的数据操作方式、更强大的统计分析能力以及更便捷的自动化流程。
在R语言的GIS生态系统中,
sf
、
sp
、
raster
、
ggplot2
和
leaflet
等包构成了核心工具集。这些包不仅支持从简单的点线面绘制到复杂的栅格数据可视化,还能处理从本地静态地图到交互式网络地图的各种需求。本文将系统地介绍R语言GIS地图绘制的实战技巧,并深入解析常见问题,帮助读者掌握高效、专业的地图制作方法。
1. R语言GIS地图绘制基础
1.1 空间数据基础概念
在开始绘制地图之前,理解空间数据的基本概念至关重要。空间数据主要分为矢量数据和栅格数据两种类型:
矢量数据
:由点、线、面等几何对象组成,适合表示离散的地理要素(如城市、道路、行政区划)。常见的矢量数据格式包括Shapefile(.shp)、GeoJSON等。
栅格数据
:由规则的网格单元组成,每个单元存储一个值,适合表示连续的地理现象(如高程、温度、降水)。常见的栅格数据格式包括GeoTIFF、ASCII Grid等。
坐标参考系统(CRS)是空间数据的核心属性,它定义了数据在地球表面的位置。常见的CRS包括:
WGS84(EPSG:4326):全球通用的经纬度坐标系
Web Mercator(EPSG:3857):网络地图常用投影
UTM(通用横轴墨卡托投影):适合区域地图的投影
1.2 核心包安装与加载
R语言GIS地图绘制主要依赖以下包:
# 安装必要的包
install.packages(c(“sf”, “sp”, “raster”, “ggplot2”, “leaflet”,
“rnaturalearth”, “rnaturalearthdata”, “dplyr”))

# 加载包
library(sf) # 简单特征对象处理
library(sp) # 旧版空间对象处理
library(raster) # 栅格数据处理
library(ggplot2) # 数据可视化
library(leaflet) # 交互式地图
library(dplyr) # 数据处理
library(rnaturalearth) # 自然地球数据
1.3 数据读取与准备
R语言可以读取多种空间数据格式。以下是读取Shapefile和GeoJSON的示例:
# 读取Shapefile
# 注意:文件路径需要根据实际情况修改
# shapefile_path <- "path/to/your/file.shp" # data_sf <- st_read(shapefile_path) # 读取GeoJSON # geojson_path <- "path/to/your/file.geojson" # data_sf <- st_read(geojson_path) # 使用rnaturalearth包获取世界地图数据 world <- ne_countries(scale = "medium", returnclass = "sf") class(world) # 查看对象类型 1.4 坐标参考系统(CRS)操作 CRS是空间数据处理的核心,正确设置和转换CRS是成功绘图的关键: # 查看当前CRS st_crs(world) # 转换CRS(例如转换为Web Mercator) world_mercator <- st_transform(world, crs = 3857) # 设置CRS(当数据没有CRS信息时) # world <- st_set_crs(world, 4326) # 检查CRS是否正确 if (is.na(st_crs(world))) { warning("数据缺少CRS信息!") } 2. 静态地图绘制技巧 2.1 基于ggplot2的静态地图绘制 ggplot2 是R语言中最强大的可视化包,结合 geom_sf() 函数可以轻松绘制专业地图: # 基础世界地图 ggplot(data = world) + geom_sf(aes(fill = pop_est), color = "white", size = 0.2) + scale_fill_viridis_c(option = "plasma", name = "人口数量") + labs(title = "世界人口分布图", subtitle = "数据来源:Natural Earth", caption = "R语言GIS地图绘制示例") + theme_minimal() + theme(legend.position = "bottom") 2.2 添加地图元素 专业地图需要包含标题、比例尺、指北针等元素: # 添加地图元素 library(ggsn) # 用于添加比例尺和指北针 # 绘制基础地图 base_map <- ggplot(data = world) + geom_sf(aes(fill = pop_est), color = "white", size = 0.2) + scale_fill_viridis_c(option = "plasma", name = "人口数量") + labs(title = "世界人口分布图") + theme_minimal() # 添加比例尺和指北针(需要指定地图边界) # 注意:ggsn包需要地图投影信息,这里仅作示例 # base_map + # north(world, location = "topright") + # scalebar(world, dist = 1000, transform = TRUE, model = "WGS84") 2.3 多图层叠加与组合 复杂地图通常需要叠加多个图层,如行政区划、道路、POI点等: # 生成示例数据:中国主要城市 china_cities <- data.frame( name = c("北京", "上海", "广州", "深圳", "成都"), lon = c(116.4074, 121.4737, 113.2644, 114.0579, 104.0668), lat = c(39.9042, 31.2304, 23.1291, 22.5431, 30.5728), population = c(2154, 2424, 1868, 1756, 2094) # 万人口 ) # 转换为sf对象 china_cities_sf <- st_as_sf(china_cities, coords = c("lon", "lat"), crs = 4326) # 绘制多图层地图 ggplot() + geom_sf(data = world, fill = "lightgray", color = "white", size = 0.1) + geom_sf(data = china_cities_sf, aes(size = population, color = name), alpha = 0.7) + geom_text(data = china_cities, aes(x = lon, y = lat, label = name), size = 3, hjust = -0.1, vjust = 0.5) + scale_size_continuous(range = c(2, 8), name = "人口(万)") + scale_color_brewer(palette = "Set1", name = "城市") + coord_sf(xlim = c(70, 140), ylim = c(15, 55)) + # 限制中国区域 labs(title = "中国主要城市分布图") + theme_minimal() + theme(legend.position = "right") 2.4 分面地图(Facet Maps) 分面地图可以展示不同时间或不同变量的空间分布: # 创建示例数据:不同年份的GDP数据 set.seed(123) years <- 2018:2020 gdp_data <- expand.grid(year = years, region = c("East", "West", "North", "South")) gdp_data$gdp <- round(runif(nrow(gdp_data), 1000, 5000)) gdp_data$lon <- gdp_data$region gdp_data$lon <- ifelse(gdp_data$region == "East", 120, ifelse(gdp_data$region == "West", 100, ifelse(gdp_data$region == "North", 116, 112))) gdp_data$lat <- ifelse(gdp_data$region == "East", 31, ifelse(gdp_data$region == "West", 30, ifelse(gdp_data$region == "North", 40, 23))) # 转换为sf对象 gdp_sf <- st_as_sf(gdp_data, coords = c("lon", "lat"), crs = 4326) # 分面地图 ggplot(data = gdp_sf) + geom_sf(data = world, fill = "lightgray", color = "white", size = 0.1) + geom_sf(aes(size = gdp, color = region), alpha = 0.8) + facet_wrap(~year, ncol = 2) + scale_size_continuous(range = c(2, 10), name = "GDP(亿元)") + scale_color_brewer(palette = "Set1", name = "区域") + labs(title = "不同年份各区域GDP分布") + theme_minimal() + theme(legend.position = "bottom") 3. 交互式地图绘制技巧 3.1 Leaflet基础应用 Leaflet是R语言中最流行的交互式地图包,支持多种底图和图层控制: # 基础Leaflet地图 leaflet() %>%
addTiles() %>% # 添加默认OpenStreetMap底图
setView(lng = 116.4074, lat = 39.9042, zoom = 5) # 设置初始视图

# 添加中国城市标记
leaflet(data = china_cities_sf) %>%
addTiles() %>%
addCircleMarkers(
radius = ~sqrt(population)/5,
color = “blue”,
fillOpacity = 0.7,
popup = ~paste(name, “人口:”, population, “万”)
) %>%
addLegend(
“bottomright”,
colors = c(“blue”),
labels = c(“城市”),
title = “图例”
)
3.2 多图层控制与底图切换
专业交互地图需要支持多图层控制和底图切换:
# 创建多图层交互地图
leaflet(data = world) %>%
addProviderTiles(“CartoDB.Positron”) %>% # 添加专业底图
addPolygons(
fillColor = ~colorNumeric(“YlOrRd”, pop_est)(pop_est),
weight = 1,
color = “white”,
fillOpacity = 0.7,
highlightOptions = highlightOptions(
weight = 3,
color = “#666”,
fillOpacity = 0.9,
bringToFront = TRUE
),
label = ~paste(name, “人口:”, pop_est),
group = “国家边界”
) %>%
addCircleMarkers(
data = china_cities_sf,
radius = ~sqrt(population)/5,
color = “red”,
fillOpacity = 0.8,
popup = ~paste(name, “人口:”, population, “万”),
group = “中国城市”
) %>%
addLayersControl(
baseGroups = c(“CartoDB.Positron”, “OpenStreetMap”, “Esri.WorldImagery”),
overlayGroups = c(“国家边界”, “中国城市”),
options = layersControlOptions(collapsed = FALSE)
) %>%
addLegend(
“bottomright”,
pal = colorNumeric(“YlOrRd”, world$pop_est),
values = ~pop_est,
title = “人口数量”,
opacity = 0.7
)
3.3 时间序列交互地图
使用
leaflet
和
shiny
可以创建动态时间序列地图:
library(shiny)
library(leaflet)
library(DT)

# Shiny UI
ui <- fluidPage( titlePanel("动态时间序列地图"), sidebarLayout( sidebarPanel( sliderInput("year", "选择年份", 2018, 2020, 2018), selectInput("region", "选择区域", choices = c("All", "East", "West", "North", "South")) ), mainPanel( leafletOutput("map", height = "500px"), dataTableOutput("table") ) ) ) # Shiny Server server <- function(input, output, session) { # 过滤数据 filtered_data <- reactive({ data <- gdp_data if (input$region != "All") { data <- data[data$region == input$region, ] } data[data$year == input$year, ] }) # 渲染地图 output$map <- renderLeaflet({ data_sf <- st_as_sf(filtered_data(), coords = c("lon", "lat"), crs = 4326) leaflet(data_sf) %>%
addTiles() %>%
addCircleMarkers(
radius = ~sqrt(gdp)/10,
color = ~colorFactor(“Set1”, region)(region),
popup = ~paste(region, “GDP:”, gdp, “亿元”)
)
})

# 渲染表格
output$table <- renderDataTable({ filtered_data() }) } # 运行应用 # shinyApp(ui, server) 4. 栅格数据可视化技巧 4.1 栅格数据基础操作 栅格数据在环境科学、遥感等领域应用广泛。以下是栅格数据的创建和基本操作: # 创建示例栅格数据 r <- raster(ncol = 10, nrow = 10) values(r) <- 1:100 # 设置栅格值 crs(r) <- CRS("+init=epsg:4326") # 设置CRS extent(r) <- c(0, 10, 0, 10) # 设置范围 # 查看栅格信息 print(r) plot(r, main = "基础栅格数据") 4.2 栅格数据可视化 使用 ggplot2 和 rasterVis 包可以创建美观的栅格地图: # 转换为数据框用于ggplot2 r_df <- as.data.frame(r, xy = TRUE) colnames(r_df) <- c("x", "y", "value") # 使用ggplot2绘制栅格 ggplot(data = r_df) + geom_raster(aes(x = x, y = y, fill = value)) + scale_fill_viridis_c(option = "viridis", name = "值") + labs(title = "栅格数据可视化", x = "经度", y = "纬度") + coord_fixed() + theme_minimal() # 使用rasterVis包(更专业的栅格可视化) library(rasterVis) levelplot(r, main = "栅格数据Levelplot", margin = FALSE) 4.3 栅格代数运算与可视化 栅格数据的强大之处在于可以进行像元级别的代数运算: # 创建第二个栅格 r2 <- raster(ncol = 10, nrow = 10) values(r2) <- runif(100, 0, 100) crs(r2) <- CRS("+init=epsg:4326") extent(r2) <- c(0, 10, 0, 10) # 栅格代数运算 r_sum <- r + r2 # 加法 r_diff <- r - r2 # 减法 r_prod <- r * r2 # 乘法 r_mask <- r > 50 # 条件筛选

# 可视化结果
par(mfrow = c(2, 2))
plot(r, main = “栅格1”)
plot(r2, main = “栅格2”)
plot(r_sum, main = “栅格1 + 栅格2”)
plot(r_mask, main = “栅格1 > 50”)
4.4 栅格重采样与重投影
# 重采样到不同分辨率
r_coarse <- aggregate(r, fact = 2, fun = mean) # 降低分辨率 r_fine <- disaggregate(r, fact = 2) # 提高分辨率(插值) # 重投影 r_projected <- projectRaster(r, crs = "+init=epsg:3857", method = "bilinear") # 可视化比较 par(mfrow = c(1, 2)) plot(r, main = "原始投影 (WGS84)") plot(r_projected, main = "重投影 (Web Mercator)") 5. 常见问题解析 5.1 坐标参考系统(CRS)问题 问题1:数据缺少CRS信息 # 问题:数据没有CRS信息 # 解决方案:手动设置CRS world <- st_read("world.shp") if (is.na(st_crs(world))) { world <- st_set_crs(world, 4326) # 假设是WGS84 } 问题2:CRS不匹配导致图层无法叠加 # 问题:两个图层CRS不同,无法正确叠加 # 解决方案:统一CRS layer1 <- st_transform(layer1, st_crs(layer2)) # 或者统一为特定CRS layer1 <- st_transform(layer1, 3857) layer2 <- st_transform(layer2, 3857) 问题3:投影变形问题 # 问题:全球地图使用WGS84投影会出现变形 # 解决方案:使用合适的投影 # 对于全球地图,使用Robinson投影或Winkel Tripel投影 world_robinson <- st_transform(world, crs = "+proj=robin") ggplot(data = world_robinson) + geom_sf() + coord_sf(crs = "+proj=3857") 5.2 数据格式与读取问题 问题1:Shapefile读取失败 # 问题:Shapefile文件不完整(缺少.dbf或.shx文件) # 解决方案:确保所有Shapefile组件文件都存在 # 或者使用其他格式如GeoJSON # 如果必须使用Shapefile,检查文件完整性 files <- list.files("path/to/shapefile", pattern = "\\.shp$|\\.dbf$|\\.shx$|\\.prj$") if (length(files) < 4) { stop("Shapefile文件不完整!") } 问题2:中文路径或中文属性乱码 # 问题:读取中文Shapefile时出现乱码 # 解决方案:指定编码 data <- st_read("path/to/file.shp", options = "ENCODING=UTF-8") # 或者 data <- st_read("path/to/file.shp", options = "ENCODING=GBK") 5.3 内存与性能问题 问题1:大数据量渲染缓慢 # 问题:大数据量地图渲染缓慢 # 解决方案1:简化几何 world_simple <- st_simplify(world, dTolerance = 1000) # 单位取决于CRS # 解决方案2:使用data.table加速数据处理 library(data.table) world_dt <- as.data.table(world) # 解决方案3:分块处理或抽样 world_sample <- world[sample(nrow(world), 100), ] # 抽样100个要素 问题2:内存不足 # 问题:处理大型栅格数据时内存不足 # 解决方案:使用raster包的内存管理功能 r <- raster("large_file.tif") # 使用块处理而不是一次性读取 values_in_memory <- readValues(r, row = 1, nrows = nrow(r)) # 或者使用rasterVis的levelplot进行分块渲染 5.4 可视化与美学问题 问题1:颜色方案选择不当 # 问题:颜色对比度不足或色盲不友好 # 解决方案:使用ColorBrewer或Viridis颜色方案 # 连续变量 ggplot(data = world) + geom_sf(aes(fill = pop_est), color = "white") + scale_fill_viridis_c(option = "plasma", name = "人口") # 色盲友好 # 分类变量 ggplot(data = world) + geom_sf(aes(fill = continent), color = "white") + scale_fill_brewer(palette = "Set2", name = "大洲") # ColorBrewer方案 问题2:图例和标签混乱 # 问题:图例位置不当或标签重叠 # 解决方案:优化图例和标签 ggplot(data = world) + geom_sf(aes(fill = pop_est), color = "white") + scale_fill_viridis_c( option = "plasma", name = "人口数量", breaks = c(0, 1e6, 1e7, 1e8), # 自定义断点 labels = c("0", "100万", "1000万", "1亿") # 自定义标签 ) + labs(title = "世界人口分布", x = "经度", y = "纬度") + theme(legend.position = "bottom", legend.key.width = unit(2, "cm")) 问题3:地图要素不完整 # 问题:缺少比例尺、指北针等专业要素 # 解决方案:使用ggspatial包 library(ggspatial) ggplot(data = world) + geom_sf(fill = "lightgray", color = "white") + annotation_north_arrow(location = "tr", which_north = "true") + annotation_scale(location = "bl", pad_x = unit(0.2, "in"), pad_y = unit(0.2, "in")) + labs(title = "带比例尺和指北针的地图") 5.5 交互式地图常见问题 问题1:Leaflet地图加载缓慢 # 问题:大数据量导致交互卡顿 # 解决方案:简化数据或使用聚类 leaflet(data = world) %>%
addTiles() %>%
addPolygons(
fillColor = ~colorNumeric(“YlOrRd”, pop_est)(pop_est),
weight = 0.5,
color = “white”,
fillOpacity = 0.6,
# 使用聚类
clusterOptions = markerClusterOptions()
)
问题2:弹出窗口(Popup)格式混乱
# 问题:Popup内容格式不美观
# 解决方案:使用HTML格式化
leaflet(data = china_cities_sf) %>%
addTiles() %>%
addCircleMarkers(
popup = ~paste0(
“

“,
“

“, name, “

“,
“

人口: “, population, “万

“,
“

坐标: “, round(st_coordinates(geometry)[1], 2), “,”,
round(st_coordinates(geometry)[2], 2), “

“,
“

”
)
)
6. 高级技巧与最佳实践
6.1 空间分析与地图结合
将空间分析结果直接可视化是R语言的优势:
# 空间连接分析
# 计算每个国家的平均海拔(假设我们有海拔数据)
# 这里用随机数据模拟
world$elevation <- runif(nrow(world), 0, 5000) # 空间聚合:按大洲汇总 continent_summary <- world %>%
group_by(continent) %>%
summarise(
total_pop = sum(pop_est),
mean_elevation = mean(elevation),
count = n()
)

# 可视化聚合结果
ggplot(data = continent_summary) +
geom_sf(aes(fill = mean_elevation), color = “white”) +
scale_fill_viridis_c(option = “magma”, name = “平均海拔(m)”) +
labs(title = “各大陆平均海拔分布”) +
theme_minimal()
6.2 自动化地图生产
使用循环或函数批量生成地图:
# 批量生成各大陆地图
continents <- unique(world$continent) for (cont in continents) { # 过滤数据 cont_data <- world %>% filter(continent == cont)

# 生成地图
p <- ggplot(data = cont_data) + geom_sf(aes(fill = pop_est), color = "white") + scale_fill_viridis_c(option = "plasma") + labs(title = paste(cont, "人口分布")) + theme_minimal() # 保存地图 ggsave(filename = paste0("map_", cont, ".png"), plot = p, width = 10, height = 8, dpi = 300) } 6.3 与外部数据源集成 # 从PostGIS数据库读取数据 library(RPostgreSQL) con <- dbConnect(PostgreSQL(), dbname = "gisdb", host = "localhost", user = "postgres", password = "password") roads <- st_read_db(con, query = "SELECT * FROM roads WHERE city = 'Beijing'") dbDisconnect(con) # 从API获取实时数据 library(httr) library(jsonlite) # 示例:从OpenWeatherMap获取天气数据 # 注意:需要API key # response <- GET("http://api.openweathermap.org/data/2.5/weather?q=Beijing&appid=YOUR_API_KEY") # weather_data <- fromJSON(content(response, "text")) 6.4 地图输出与分享 # 高分辨率输出 ggsave("high_res_map.png", width = 12, height = 8, dpi = 600, bg = "white") # PDF矢量输出(适合印刷) ggsave("vector_map.pdf", width = 12, height = 8, device = cairo_pdf) # 交互式HTML输出 library(htmlwidgets) saveWidget(leaflet_map, "interactive_map.html") # 在R Markdown中嵌入地图 # ```{r} # leaflet(data = world) %>% addTiles()
# “`
7. 总结
R语言为GIS地图绘制提供了强大而灵活的解决方案。通过掌握
sf
、
ggplot2
和
leaflet
等核心包的使用,结合空间分析和数据处理技巧,可以创建从简单静态地图到复杂交互式应用的各种地图产品。
关键要点:
数据准备
:确保空间数据的CRS正确,数据格式兼容
可视化选择
:根据需求选择静态或交互式地图,使用合适的颜色方案
性能优化
:处理大数据时注意简化几何、分块处理
专业性
:添加必要的地图元素(比例尺、指北针、图例)
自动化
:使用函数和循环批量生产地图
通过本文介绍的技巧和问题解决方案,读者可以显著提高R语言GIS地图绘制的效率和质量,制作出专业级别的空间可视化作品。