地图相关R语言可视化重点关注

ggplot2优雅的在地图上添加采样点信息

2021-09-14  本文已影响0人  R语言数据分析指南

最近有朋友问怎么给地图上用饼图添加采样信息,本节就来介绍一下,满满的都是细节

下载并加载R包

package.list=c("tidyverse","ggspatial","ggsci",
               "scatterpie","ggrepel","tibble","ggpp","ComplexHeatmap")

for (package in package.list) {
  if (!require(package,character.only=T, quietly=T)) {
    install.packages(package)
    library(package, character.only=T)
  }
}

获取地图信息

world_map <- map_data("world") %>% dplyr::rename(country=region) %>%
  mutate(country=str_replace(country,"Taiwan","China")) %>% 
  filter(country != "Antarctica") 

构建需要展示的国家数据

map <- c("Australia","China","Denmark","Finland","South Africa",
         "France","Germany","Russia","Egypt",
         "Hungary","Japan","Brazil","UK","USA","Canada") %>% 
  as.data.frame() %>% dplyr::rename(country=".") %>% 
  mutate(country=str_replace(country,"Korea","South Korea")) %>% 
  mutate(cou=country)

结合采样信息和地图信息

city <- read.delim("pie.xls",row.names = 1) %>% 
  t() %>% as.data.frame() %>% rownames_to_column(var="city") %>%
  left_join(.,read.delim("map.xls"),by="city")

绘制地图

geom_scatterpie在地图上添加多个饼图

world_map %>% left_join(.,map,by="country") %>% 
  ggplot()+
  geom_polygon(aes(x = long, y = lat,group = group,fill= cou),
               color = "black",size = 0.2,show.legend = F)+
  geom_scatterpie(data=city,aes(x=longitude,y=latitude,r=3),
                  cols=c("B","C","D"),show.legend=F)+
  geom_text_repel(data=city,aes(x=longitude,y=latitude,label=city),
                  min.segment.length=0,seed = 42,box.padding=1.2,
                  size=4,show.legend = F)+
  scale_fill_simpsons(na.value="gray70")+
  theme_void()+
  theme(plot.background = element_rect(fill="#5BBCD6",
                                       color="transparent",size = 1))+
  annotation_north_arrow(location = "bl",pad_x = unit(0.2,"in"),  
                         pad_y = unit(6,"in"),
                         style = north_arrow_nautical(fill = c("grey40","white"),
                                                      line_col = "grey20"))

添加饼图图例

由于geom_polygon & geom_scatterpie都会产生图例,无法只选择一个;因此全部设置show.legend = F;最后通过Legend( )重新绘制图例

lgd = Legend(labels = c("B","C","D"),
             legend_gp = gpar(fill=c("#FED439FF","#709AE1FF","#197EC0FF")),
             grid_width = unit(7,"mm"),grid_height=unit(7,"mm"))

draw(lgd,x = unit(0.99,"npc"),y = unit(0.6,"npc"),just = c("right","top"))

喜欢的小伙伴欢迎关注我的公众号

R语言数据分析指南,持续分享数据可视化的经典案例及一些生信知识,希望对大家有所帮助

上一篇下一篇

猜你喜欢

热点阅读