如何在ggplot2世界地图中将图例单值改为数值范围并合并标度
解决方案:调整ggplot2地图图例为数值范围并合并颜色与尺寸图例
修改后的完整代码
library(ggplot2) library(dplyr) library(sf) library(rnaturalearth) library(rnaturalearthdata) # 数据分箱处理:将连续数值转为区间因子 merged_data <- merged_data %>% mutate( yield_bin = cut( median_mafruit, breaks = c(0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0), labels = c("0-0.5", "0.5-1.0", "1.0-1.5", "1.5-2.0", "2.0-2.5", "2.5-3.0", "3.0-3.5", "3.5-4.0"), include.lowest = TRUE ) ) merged_data_sf <- st_as_sf(merged_data, coords = c("longitude", "latitude"), crs = 4326) world <- ne_countries(scale = "medium", returnclass = "sf") colors <- c("#E31A1C", "#FF7F00", "#FDBF6F", "#E9E4A6", "#A4D4A9", "#B2DF8A", "#33A02C", "#1F78B4") # 为每个区间设置对应尺寸,按区间从小到大递增 size_values <- seq(1, 5, length.out = length(colors)) p1 <- ggplot() + geom_sf(data = world, fill = "grey87", color = "white") + # 映射分箱后的变量到color和size geom_sf(data = merged_data_sf, aes(size = yield_bin, color = yield_bin), alpha = 0.7) + labs( title = "Data1", subtitle = "10 years", x = "Longitude (°)", y = "Latitude (°)" ) + scale_color_manual(values = colors) + scale_size_manual(values = size_values) + coord_sf( xlim = c(-4.4833, 7.25), ylim = c(42.45, 47.21), expand = FALSE ) + theme_minimal() + theme( plot.title = element_text(size = 14, face = "bold"), plot.subtitle = element_text(size = 12, face = "italic"), legend.title = element_text(size = 10), legend.text = element_text(size = 8), legend.key.size = unit(0.5, "cm"), legend.spacing.x = unit(0.5, "cm"), legend.spacing.y = unit(0.5, "cm") ) + # 合并颜色和尺寸图例 guides( color = guide_legend(title = bquote("Yield (t·ha"^-1*")"), order = 1), size = guide_legend(title = bquote("Yield (t·ha"^-1*")"), order = 1) ) print(p1)
关键修改说明
- 数据分箱:用
cut()函数将连续的median_mafruit转为区间因子,直接生成数值范围标签,这是实现范围图例的核心。 - 映射调整:将
aes()中的size和color统一映射到分箱后的yield_bin因子,让ggplot自动识别两个尺度的关联。 - 尺度匹配:通过
scale_color_manual和scale_size_manual为每个区间指定对应的颜色和尺寸,保证视觉属性与数值范围一一对应。 - 图例合并:在
guides()中给两个尺度设置相同的标题和顺序,ggplot会将它们合并为一个图例,每个条目同时展示对应颜色和尺寸。
内容的提问来源于stack exchange,提问作者Nightowl
相关产品推荐
相关产品推荐

