R绘制美国州地图时如何为每个州添加唯一State Codes标签
问题描述
我使用R语言绘制美国州地图,想要给每个州标注数据集中的州代码(State Codes)变量,但调用geom_text或者geom_text_repel函数时,每个州都会出现多个重复标签,请问怎么解决这个问题,让每个州仅显示1个对应的州代码缩写?
我的实现代码如下:
library(tidyverse) library(maps) library(wesanderson) library(hrbrthemes) ggplot(data = data, mapping = aes(x = long, y = lat, group = group, fill = black_percentage)) + geom_polygon(col = "black") + geom_text(aes(label = black_percentage)) + theme_void() + theme(legend.position = "bottom", legend.title = element_blank(), plot.title = element_text(hjust = 0.5, family = "Times", face = "bold"), plot.subtitle = element_text(hjust = 0.5, family = "Times", face = "italic"), plot.caption = element_text(family = "Times", face = "italic"), legend.key.height = unit(0.85, "cm"), legend.key.width = unit(0.85, "cm")) + scale_fill_gradient(low = "#E6A0C4", high = "#7294D4") + labs(title = "Percentage of Black People, US States 2018", subtitle = "Pink colors represent lower percentages. Light-blue colors represents higer percentages") + ggsave("failed_map.png")
解决方案
问题原因
用于绘制州轮廓的数据集是多边形顶点数据,每个州对应N行顶点坐标记录,直接调用geom_text会在每一个顶点位置生成标签,自然会出现大量重复内容。
操作步骤
- 先统计每个州的中心点坐标,生成每个州仅1行的数据集:
# 请将代码中的state、state_code替换为你实际数据集里对应的州名、州代码字段名 state_centers <- data %>% group_by(state, state_code, black_percentage) %>% summarise( long = mean(long, na.rm = TRUE), lat = mean(lat, na.rm = TRUE), .groups = "drop" )
- 修改ggplot代码,
geom_text单独传入中心点数据集,取消继承全局的group映射:
ggplot(data = data, mapping = aes(x = long, y = lat, group = group, fill = black_percentage)) + geom_polygon(col = "black") + # 单独用中心点数据集标注,group=NULL取消全局分组映射避免出错 geom_text(data = state_centers, aes(label = state_code, group = NULL)) + # 如果标签有重叠,可替换为以下代码使用geom_text_repel自动调整位置 # geom_text_repel(data = state_centers, aes(label = state_code, group = NULL)) + theme_void() + theme(legend.position = "bottom", legend.title = element_blank(), plot.title = element_text(hjust = 0.5, family = "Times", face = "bold"), plot.subtitle = element_text(hjust = 0.5, family = "Times", face = "italic"), plot.caption = element_text(family = "Times", face = "italic"), legend.key.height = unit(0.85, "cm"), legend.key.width = unit(0.85, "cm")) + scale_fill_gradient(low = "#E6A0C4", high = "#7294D4") + labs(title = "2018年美国各州黑人群体占比", subtitle = "粉色代表占比较低,浅蓝色代表占比较高") # 建议ggsave单独调用,不要直接加在ggplot链式调用末尾,避免偶发保存错误 ggsave("fixed_map.png", width = 12, height = 8)
内容的提问来源于stack exchange,提问作者Gaspar
相关产品推荐
相关产品推荐

