You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为ggmap、ggplot及geom_sf_text绘制的文本添加阴影

实现ggmap中文本的白色细边框效果

你可以通过叠加两层geom_sf_text来实现文本的白色细边框效果,具体方法如下:

创建多边形和点

library(tibble); library(sf); library(dplyr); library(ggmap); library(ggplot2)

lon <- c(-2.28693776739262, -2.28775699708943, -2.28703948292762, -2.29244089927134, -2.29166515832837, -2.30186223039892, -2.30309391144779, -2.3056785372324, -2.30317524849752, -2.29377665148526, -2.28749981389358, -2.28693776739262)
lat <- c(55.8178060589878, 55.8176446224019, 55.8143145424301, 55.8134429653489, 55.8125449362038, 55.8111356982306, 55.8143414682509, 55.8151103263674, 55.8178015760052, 55.8220786729108, 55.8200414980507, 55.8178060589878)

df <- tibble(lon, lat)

poly <- df %>% 
  st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
  summarise(geometry = st_combine(geometry)) %>%
  st_cast("POLYGON")

lon <- c(-2.290673, -2.297313, -2.298313)
lat <- c(55.815681, 55.818586, 55.814384)

df <- tibble(lon, lat)

poly_points <- df %>% 
  st_as_sf(coords = c("lon", "lat"), crs = 4326) %>%
  summarise(geometry = st_combine(geometry)) %>%
  st_cast("POINT")

poly_points$name <- c("point1","point2","point3")

poly_points %>% 
  st_combine %>% 
  st_centroid -> 
  poly_points_centroid

修改后的ggmap绘图代码

map <- get_map(location = st_coordinates(poly_points_centroid), zoom = 15, maptype = "satellite")

ggmap(map, extent = "device", legend = "right") +
  geom_sf(data=poly, color='green', inherit.aes = FALSE, fill = NA, size = 1.5) +
  # 先绘制白色底层文本作为边框,字号比上层稍大
  geom_sf_text(data=poly_points, aes(label = name), inherit.aes = FALSE, show.legend = FALSE, size = 4.5, color = "white") +
  # 再绘制红色目标文本,覆盖在白色文本之上
  geom_sf_text(data=poly_points, aes(label = name), inherit.aes = FALSE, show.legend = FALSE, size = 4, color = "red") +
  theme_nothing() +
  theme(plot.margin = margin(0.16, 3.8, 1, 1, "cm"))

效果说明

  • 调整底层白色文本的size参数可控制边框粗细:字号差值越大,边框越粗;差值越小,边框越细。这里设置size=4.5,比上层红色文本的size=4大0.5,刚好形成细边框效果。
  • 两层文本使用相同数据源和位置,确保完全对齐,白色边缘从红色文本四周露出,模拟出带白色边框的阴影效果。

内容的提问来源于stack exchange,提问作者luciano

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 19:13:15