R语言usmap绘图:仅为阴影州标注缩写及设置双色标题方法
实现方案
你需要先安装加载ggtext包用于实现富文本双色标题,未安装可先运行install.packages("ggtext")。
选中州标注实现思路
usmap自带的statepop数据集已包含各州缩写、中心经纬度信息,你只需要先筛选出标记为选中的州,通过usmap_transform()将经纬度转换为usmap适配的Albers投影坐标,再叠加geom_text层即可仅在目标州中心标注黄色缩写。
双色标题实现思路
用ggtext提供的element_markdown()渲染标题文本,将序号部分用HTML span标签指定为紫色,其余部分保留黑色即可,需把原theme配置里的element_text替换为element_markdown支持富文本解析。
修改后完整代码
library(usmap) library(ggplot2) library(dplyr) library(stringr) library(ggtext) # 原有数据处理逻辑 dt <- statepop %>% dplyr::mutate(selected = factor(ifelse(full %in% stringr::str_pad(c(s.cls.list[[i]]$State), 5, pad = "0"), "1", "0"))) # 提取选中州的适配投影坐标 selected_states <- dt %>% filter(selected == "1") selected_coords <- usmap_transform(selected_states, input_names = c("lon", "lat")) # 绘图逻辑 s.plot <- usmap::plot_usmap(data = dt, values = "selected", color = "grey") + ggplot2::scale_fill_manual(values = c("#E5E4E2", "purple"), name = length(c(s.cls.list[[i]]$State))) + # 叠加选中州的黄色缩写标注 geom_text(data = selected_coords, aes(x = x, y = y, label = abbr), color = "yellow", fontface = "bold", size = 3.5) + # 双色标题配置 labs(title = paste0("component : <span style='color:purple'>", i, "</span>")) + theme( plot.title = element_markdown(size = 14, face = "bold", hjust = 0.5) )
内容的提问来源于stack exchange,提问作者Mathica
相关产品推荐
相关产品推荐

