# 安装并加载必要的包
if (!require("mapchina")) install.packages("mapchina")
if (!require("tidyverse")) install.packages("tidyverse")
if (!require("sf")) install.packages("sf")
if (!require("ggspatial")) install.packages("ggspatial")
if (!require("scales")) install.packages("scales")
library(mapchina)
library(tidyverse)
library(sf)
library(ggspatial)
library(scales)
# 获取中国地图数据并过滤出江苏省
province <- china %>%
filter(Name_Province == "江苏省")
# 聚合计算县级几何体
counties <- province %>%
group_by(Name_County) %>%
summarise(geometry = st_union(geometry), .groups = "drop") %>%
mutate(
is_jiangning = ifelse(Name_County == "江宁区", TRUE, FALSE) # 标识江宁区
)
# 聚合计算市级几何体
cities <- province %>%
group_by(Name_Perfecture) %>%
summarise(geometry = st_union(geometry), .groups = "drop")
# 仅保留江宁气象站数据
stations_df <- data.frame(
name = "江宁",
id = "58233",
lat = 31.9534,
lon = 118.8399
)
# 创建地图对象
map_plot <- ggplot() +
# 绘制所有县级区域,江宁区红色填充
geom_sf(data = counties,
aes(fill = is_jiangning),
linetype = "solid",
size = 0.5,
color = "white") +
# 绘制市级边界
geom_sf(data = cities,
alpha = 0,
linetype = "solid",
size = 1,
color = "black") +
# 设置省级边界
geom_sf(data = province,
alpha = 0,
linetype = "dashed",
size = 1.2,
color = "gray30") +
# 标记江宁气象站位置(黑色圈白色填充,无编号)
geom_point(data = stations_df,
aes(x = lon, y = lat),
color = "black", # 黑色边框
fill = "white", # 白色填充
shape = 21, # 带边框的圆形
size = 2.5, # 大小
stroke = 1) + # 边框粗细
# 显示经纬度坐标轴
ggspatial::annotation_scale(location = "bl", width_hint = 0.4) +
ggspatial::annotation_north_arrow(location = "tl", which_north = "true",
pad_x = unit(0.5, "in"), pad_y = unit(0.5, "in"),
style = ggspatial::north_arrow_fancy_orienteering()) +
# 设置颜色方案:江宁区红色,其他县灰色
scale_fill_manual(values = c("TRUE" = "red", "FALSE" = "lightblue"),
guide = "none") +
# 配置经纬度显示格式,使用°和E/N标注
scale_x_continuous(name = "经度", labels = function(x) paste0(x, "°E")) +
scale_y_continuous(name = "纬度", labels = function(x) paste0(x, "°N")) +
# 设置主题
theme_bw() +
theme(
plot.title = element_text(hjust = 0.5, size = 14),
axis.text = element_text(size = 10),
axis.ticks = element_line(),
panel.grid.major = element_line(color = "gray90", linewidth = 0.3)
) +
# 添加标题
ggtitle("江苏省江宁区及58233气象站位置")
# 指定存储路径
output_path <- "D:/1 收留夹"
# 检查路径是否存在,不存在则创建
if (!dir.exists(output_path)) {
dir.create(output_path, recursive = TRUE, showWarnings = FALSE)
}
# 导出图片
ggsave(
filename = file.path(output_path, "江宁终.png"),
plot = map_plot,
width = 10,
height = 8,
dpi = 300,
units = "in"
)
# 提示信息
cat("图片已成功导出至:", file.path(output_path, "江宁终.png"), "\n")
cat("\n气象站信息:\n")
print(stations_df)