library(sf)
library(ggplot2)
library(dplyr)
library(ggspatial)
library(xlsx)
# 读取地理数据
china_data <- st_read("C:/Users/DELL/Desktop/RMap/China/China1.geojson")%>%
st_make_valid() %>%
st_transform(4326) # 确保使用WGS84坐标系
# 读取Excel数据
workbook <- "C:/Users/DELL/Desktop/RXlsx/Map/G2Map.xlsx"
excelMap <- read.xlsx(workbook, 1)
# 创建示例数据
province_data <- data.frame(
Province = excelMap$Province1,
aGraph = excelMap$aGraph2004
) %>% na.omit()
# 合并数据
merged_data <- china_data %>%
left_join(province_data, by = c("fullname" = "Province"))
# 定义颜色和断点参数 --------------------------------------------------------
colors <- c(
"#00441b", # [-0.2, -0.1) 深绿
"#238b45", # [-0.1, -0.05) 中绿
"#74c476", # [-0.05, 0) 浅绿
"#fb6a4a", # [0, 0.5) 浅红 <- 关键修正点
"#ef3b2c", # [0.5, 1) 中红
"#99000d" # [1, 1.5] 深红
)
breaks <- c(-0.2, -0.10, -0.05, 0, 0.5, 1, 1.5) # 7个断点形成6个区间
# 修改颜色定义方式
# color_mapping <- data.frame(
# from = c(-0.2, -0.1, -0.05, 0, 0.5, 1),
# to = c(-0.1, -0.05, 0, 0.5, 1, 1.5),
# color = c("#00441b", "#238b45", "#74c476", "#fb6a4a", "#ef3b2c", "#99000d")
# )
#
# # 生成动态颜色向量
# colors <- color_mapping$color
# breaks <- unique(c(color_mapping$from, max(color_mapping$to)))
# 创建地图 ---------------------------------------------------------------
mainplot <- ggplot() +
geom_sf(
data = merged_data,
aes(fill = aGraph) # 直接使用连续变量
) +
# 使用分步颜色标度
# scale_fill_stepsn(
# name = "指标值",
# colors = colors,
# breaks = breaks,
# limits = c(-0.2, 1.5), # 需要同步修改范围
# labels = scales::number_format(accuracy = 0.01), # 精确到小数点后2位
# guide = guide_colorsteps(
# title.position = "top",
# direction = "horizontal",
# barwidth = unit(10, "cm"), # 加长颜色条
# show.limits = FALSE, # 显示极值标签
# ),
# na.value = "#FFFFFF"
# ) +
scale_fill_stepsn(
colors = colors,
breaks = breaks,
limits = c(-0.2, 1.5),
labels = scales::number_format(accuracy = 0.01),
# 新增关键参数
na.value = "#FFFFFF",
# 强制采用左闭右开
right = FALSE, # 与cut()保持同步
# 精确控制颜色分配
#断点分配标准化
values = scales::rescale(
c(-0.2, -0.1, -0.05, 0, 0.5, 1),
to = c(0, 1)
),
guide = guide_colorsteps(
title.position = "right",
direction = "horizontal",
barwidth = unit(8, "cm"), # 加长颜色条
show.limits = TRUE, # 显示极值标签
),
) +
# 坐标系统及刻度
coord_sf() +
scale_x_continuous(
breaks = seq(80, 130, by = 10),
labels = function(x) paste0(x, "°E")
) +
scale_y_continuous(
breaks = seq(20, 50, by = 5),
labels = function(x) paste0(x, "°N")
) +
# 调整主题样式
labs(title = "a图 上升阶段年均变化量地图") +
theme_void() +
theme(
plot.title = element_text(hjust = 0.5, size = 16, face = "bold"),
legend.position = "bottom", # 图例放在底部
legend.title = element_text(size = 12),
legend.text = element_text(size = 10),
panel.border = element_rect(color = "black", fill = NA, size = 1),
axis.text = element_text(color = "black", size = 10, face = "bold")
)
print(mainplot)
修改和优化上述代码的图例,1.要求图例为横向,标题位于位于右侧中间位置,此代码中图例标题位置偏下;2.把图例放置图中左下角