在R语言美国地图上绘制带分类的散点饼图(求助分类颜色显示)
为地图散点饼图的分类设置独立颜色
你当前代码用的是geom_point而非scatterpie包的专属函数,因此无法实现饼图分类的颜色区分。以下是修正方案:
关键调整点
- 加载
scatterpie包 - 将散点饼数据转换为宽格式(每个区域一行,各分类作为单独列)
- 使用
geom_scatterpie绘制饼图,通过fill映射分类并自定义颜色
完整修正代码
library(sf) library(ggplot2) library(maps) library(tidyverse) library(scatterpie) # 新增加载scatterpie包 # 加载美国地图数据 us_map <- st_as_sf(maps::map("state", plot = FALSE, fill = TRUE)) regions_data <- list( Northeast = c("DE", "ME", "MD", "MA", "NJ", "CT", "NY", "PA"), OhioValley = c("IL", "IN", "KY", "MO", "OH", "TN", "WV"), RockiesPlains = c("MT", "NE", "ND", "SD", "WY"), South = c("AR", "KS", "LA", "MS", "OK", "TX"), Northwest = c("WA", "OR", "ID"), Southwest = c("AZ", "CO", "NM", "UT"), West = "CA", Southeast = c("AL", "GA", "FL", "NC", "SC", "VA"), UpperMidwest = c("IA", "MN", "WI", "MI") ) mapping_df <- enframe(regions_data, name = "region", value = "state") %>% unnest(state) %>% left_join(data.frame(state.abb, state.name), by = c("state" = "state.abb")) %>% mutate(state.name = tolower(state.name)) us_map_regions <- left_join(us_map, mapping_df, by = c("ID" = "state.name")) # 整理散点饼数据:转换为宽格式 scatterpie_data <- data.frame( region = c("Northeast", "Northeast", "Northeast", "OhioValley", "OhioValley", "OhioValley"), category = rep(c("Diploid", "Polyploid", "Unknown"), each = 2), value = c(30, 40, 30, 20, 30, 50), lon = c(-75, -75, -75, -90, -90, -90), lat = c(42, 42, 42, 38, 38, 38) ) %>% pivot_wider(names_from = category, values_from = value) %>% distinct(region, lon, lat, .keep_all = TRUE) # 去重保留每个区域的唯一坐标和数值 # 绘制地图+散点饼图 ggplot() + geom_sf(data = us_map_regions, aes(fill = region), alpha = 0.7) + theme_minimal() + labs(title = "美国区域地图与散点饼图", subtitle = "自定义区域划分") + theme(legend.position = "bottom") + geom_sf_text(data = us_map_regions, aes(label = region), color = "black", size = 3) + # 使用scatterpie绘制饼图 geom_scatterpie(data = scatterpie_data, aes(x = lon, y = lat, r = 1.5), # r控制饼图半径 cols = c("Diploid", "Polyploid", "Unknown"), # 指定饼图的分类列 alpha = 0.8) + # 自定义分类颜色 scale_fill_manual(name = "倍性分类", values = c(Diploid = "#1f77b4", Polyploid = "#ff7f0e", Unknown = "#2ca02c")) + coord_sf(datum = NA)
代码解释
- 数据格式转换:用
pivot_wider将长格式数据转为宽格式,确保每个区域对应一行,方便scatterpie识别各分类的数值 - geom_scatterpie参数:
cols指定参与饼图绘制的分类列,r控制饼图大小;通过fill映射分类(自动关联scale_fill_manual的颜色) - 颜色自定义:
scale_fill_manual为每个分类设置独立颜色,同时修改图例名称
内容的提问来源于stack exchange,提问作者PloidyPhD
相关产品推荐
相关产品推荐

