ggplot2投影地图:移除轴线并将轴标签移至网格旁的方法
解决ggplot2投影地图移除轴线并调整轴标签位置的问题
我来帮你搞定这个ggplot2地图的调整需求!咱们一步步来实现移除轴线、把轴标签放在网格线旁的效果,先把你提供的可复现数据补全,再修改绘图代码:
1. 补全可复现数据
你给出的adf数据结构不完整,我帮你补全了必要的字段(比如group和id),方便后续转换为sf对象或直接绘图:
adf <- structure( list( long = c(249.999938964844, 152.500122070312, 152.500122070312, 249.999938964844, 249.999938964844), lat = c(12.5000610351562, 12.5000610351562, 80, 80, 12.5000610351562), order = 1:5, hole = c(FALSE, FALSE, FALSE, FALSE, FALSE), piece = structure(c(1L, 1L, 1L, 1L, 1L), .Label = "1", class = "factor"), group = structure(c(1L, 1L, 1L, 1L, 1L), .Label = "1", class = "factor"), id = structure(c(1L, 1L, 1L, 1L, 1L), .Label = "1", class = "factor") ), class = c("tbl_df", "tbl", "data.frame") )
2. 完整调整后的绘图代码
这里用sf包处理地理数据(更适合投影地图),然后通过theme参数实现你的需求:
library(ggplot2) library(sf) # 将数据转换为sf对象(适合地理投影) sf_df <- st_polygon(list(cbind(adf$long, adf$lat))) %>% st_sfc() %>% st_sf() # 绘制投影地图并调整样式 ggplot(sf_df) + geom_sf(fill = "lightblue", color = "black") + # 设置你需要的投影坐标系(这里用兰伯特等面积投影作为示例) coord_sf(crs = "+proj=laea +lat_0=50 +lon_0=-100 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs") + # 核心样式调整 theme( # 移除轴线 axis.line = element_blank(), # 调整轴标签位置,让它们贴近网格线 axis.text.x = element_text(hjust = 0.5, margin = margin(t = -10)), # 向上移动x轴标签 axis.text.y = element_text(vjust = 0.5, margin = margin(r = -10)), # 向左移动y轴标签 # 保留网格线作为参照 panel.grid.major = element_line(color = "gray80", linetype = "dashed"), # 设置背景为白色(可选) panel.background = element_rect(fill = "white") ) + # 可选:自定义轴标签格式(比如转换为公里单位) scale_x_continuous(labels = function(x) paste0(round(x/1000, 1), "km")) + scale_y_continuous(labels = function(x) paste0(round(x/1000, 1), "km"))
关键参数说明
- 移除轴线:用
axis.line = element_blank()彻底去掉x、y轴的轴线 - 调整标签位置:通过
axis.text.x/y的margin参数调整标签与绘图区域的距离,t = -10表示向上移动10pt,r = -10表示向左移动10pt,你可以根据地图实际大小微调这个数值 - 投影设置:
coord_sf的crs参数替换为你需要的投影坐标系即可 - 如果不用
sf对象,直接用geom_polygon(aes(x=long, y=lat)),配合coord_map()也能实现类似效果,样式调整的theme参数完全通用
内容的提问来源于stack exchange,提问作者Lily Nature
相关产品推荐
相关产品推荐

