如何用R语言ggplot2绘制六边形瓦片网格地图
把世界瓦片网格地图从矩形改成六边形的实现方法
核心思路
要将矩形瓦片转为六边形,需要调整坐标实现交错排列,并使用支持六边形绘制的geom图层。这里推荐用ggforce包的geom_hexagon,它能直接生成规则六边形,无需手动绘制多边形顶点。
修改步骤
- 安装并加载
ggforce包:如果还没安装,先执行安装命令,再加载包。 - 调整坐标偏移:六边形网格需要奇数行的x坐标偏移0.5,让瓦片能交错对齐。
- 替换图层:把
geom_tile换成geom_hexagon,同时调整文本的x坐标映射,保证文字居中在六边形内。
修改后的完整代码
library(tidyverse) library(ggplot2) library(tidytuesdayR) library(highcharter) library(maps) library(jsonlite) library(showtext) library(showtextdb) library(ggtext) library(ggforce) # 新增:加载ggforce包 world_grid <- read_csv("worldtilegrid.txt") tt <- tidytuesdayR::tt_load('2023-05-30') tt <- tt$centenarians countries_count <- tt %>% group_by(place_of_death_or_residence) %>% mutate(place_of_death_or_residence = case_when(place_of_death_or_residence == "France (French Guiana)" ~ "France", place_of_death_or_residence == "France (Martinique)" ~ "France", place_of_death_or_residence == "France (Saint Barthélemy)" ~ "France", place_of_death_or_residence == "United States" ~ "United States of America", place_of_death_or_residence == "United Kingdom" ~ "Great Britain and Northern Ireland", place_of_death_or_residence == "Puerto Rico" ~ "United States of America", TRUE ~ place_of_death_or_residence)) %>% summarise(count = n()) %>% as.data.frame() data_to_plot <- world_grid %>% left_join(countries_count, by = c("name" = "place_of_death_or_residence")) %>% # 新增:调整x坐标,奇数行偏移0.5,适配六边形交错排列 mutate(x_hex = ifelse(y %% 2 == 1, x + 0.5, x)) plot <- ggplot() + # 替换geom_tile为geom_hexagon,设置半径,映射调整后的x坐标 geom_hexagon(data = data_to_plot, aes(x = x_hex, y = y, fill = count), color = "#ffffff", radius = 0.5) + # 文本的x坐标也用调整后的x_hex,保证居中 geom_text(data = data_to_plot, aes(x = x_hex, y = y, label = alpha.2), color = "#ffffff", alpha = 0.5, family = "caption", size = 25) + scale_y_reverse() + scale_fill_continuous(na.value = "gray", low = "#7F3C8D", high = "#80BA5A", guide = "colorbar") + theme_void() + labs(fill = "Count", title = "Verified Oldest People Around the World", subtitle = "This map demonstrates the distribution of the place of birth or residence<br>of the verified 100 oldest people across countries.") + theme(plot.title = element_markdown(size = 110, hjust = 0.5, family = "plottitle", linewidth = 0.1), plot.subtitle = element_markdown(size = 80, hjust = 0.5, family = "title", lineheight = 0.2), plot.background = element_rect(fill = "#dedad2", color = NA), panel.border = element_blank(), legend.title = element_markdown(size = 65, family = "caption", vjust = 0.75), legend.text = element_text(size = 40, family = "caption"), legend.spacing.x = unit(0.2, 'cm'), legend.spacing.y = unit(0.2, 'cm'), legend.direction = "horizontal", legend.position = c(0.2, 0.2)) # 查看绘图 plot
关键说明
geom_hexagon的radius设为0.5,刚好和原矩形瓦片的尺寸匹配,保证瓦片之间紧密排列。- 奇数行x偏移0.5是六边形网格的标准布局方式,能避免瓦片重叠,实现交错效果。
- 文本的x坐标同步调整,确保每个国家的缩写文字刚好落在六边形中心。
内容的提问来源于stack exchange,提问作者mzkrc
相关产品推荐
相关产品推荐

