g
gtrobot
V1
2022/04/13阅读:40主题:全栈蓝
R语言画中国地图-新方法
1. 我的本期总结
# 使用sf包中的st_read函数读取【阿里云数据可视化平台】的json格式地图数据
# 使用readxl包中的read_xls函数读取xls数据
# 使用runif函数生成n个均匀分布随机数
# 使用factor设置某向量的levels
# 使用geom_sf函数画地图
# 使用fill属性设置填充色为NA
# 使用coord_sf函数转换坐标系,4326 (WGS 1984) -> 21479 (Beijing 1954 / Gauss-Kruger 19N)
# 使用ylim函数设置Y轴坐标范围
# 使用crs属性设置转换的坐标系EPSG名称
# 使用ggspatial包中的annotation_north_arrow函数添加指北针
# 使用ggspatial包中的annotation_scale函数添加比例尺
# 使用theme_test函数设置画图主题
# 使用theme设置主题样式
# 使用axis.text属性设置坐标轴所有文本样式
# 使用axis.ticks属性设置坐标轴轴须样式
# 使用axis.title属性设置坐标轴标题样式
# 使用cowplot包中的ggdraw和draw_plot函数画子图
❝注:总结里的包和函数不一定在下文使用,「试错过程」中出现的。
❞
2. 读取在线数据
library(tidyverse)
library(readxl)
library(sf)
library(ggspatial)
library(cowplot)
library(ggtext)
china_map <- st_read('https://geo.datav.aliyun.com/areas_v2/bound/100000_full.json')[c('adcode','name','geometry')]
china_data <- read_xls('省会.xls')
china_data$Value <- runif(n=34,min = 20,max = 100)
china_data$Type <- c(rep(c('T1','T2','T3'),each=11),'T3')
china_data$`geographical region` <- factor(china_data$`geographical region`,levels = c('Northeast China','North China','Northwest China','Southwest China','Central China','East China','South China'))
china_data_sf <- st_as_sf(china_data,coords = c('long','lat'),crs=4326)
map_color <- c('#F9E6BE','#C7E7F2','#B5BDE1','#BBDFD1','#EEBCD5','#BBDDAB','#F8BCB2')
画中国地图
# 大图
map <- ggplot()+
geom_sf(data = china_map,fill='NA',colour='black')+
geom_sf(data = china_data_sf,mapping = aes(size=Value,fill=Type),shape=21)+
scale_fill_manual(values = c('#E21C21','#3A7CB5','#51AE4F'))+
coord_sf(ylim = c(2000000,6000000),crs = 21479)+
annotation_north_arrow(location = 't',style = north_arrow_fancy_orienteering())+
annotation_scale()+
labs(caption = "Visualization by <span style='color:#DD6449'>gtrobot</span>")+
theme(axis.text = element_text(colour = 'black'),
panel.background = element_rect(fill='NA'),
panel.grid.major = element_line(colour = 'grey80',size = 0.2),
plot.caption = element_markdown(face = 'bold'))
#小图
sub_map <- ggplot()+
geom_sf(data = china_map,fill='NA')+
guides(fill='none')+
coord_sf(xlim = c(-5000,1700000),
ylim = c(400000,2500000),
crs = 21479)+
theme(axis.text = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank(),
panel.background = element_blank(),
panel.grid = element_blank(),
panel.border = element_rect(fill = 'NA',colour = 'black'))
合并大小图
ggdraw()+
draw_plot(plot = map)+
draw_plot(plot = sub_map,x=0.78,y=0.1,width = 0.15,height = 0.2)
ggsave('china_map.pdf',width = 8,height = 6)

作者介绍
g
gtrobot
V1