其他
使用ggbump带你绘制更加精美的地图
欢迎关注R语言数据分析指南
❝好久没有更新文档了,本节继续来介绍绘图文档,下面通过一个绘制地图的小例子来展示如何通过「ggbump」绘制凹凸图来对地图进行进一步展示
❞
加载R包
library(tidyverse)
library(sf)
library(rnaturalearth)
library(rnaturalearthdata)
library(datawizard)
library(ggbump)
定义主题
theme_niwot <- function() {
theme_void() +
theme(
plot.background = element_rect(fill="lightblue1"),
plot.title = element_text(size = 18, hjust=0.5),
axis.text.y.left = element_blank(),
axis.text.x.bottom = element_blank(),
legend.position = "none"
)
}
获取地图数据
map <- ne_countries(scale = "medium", returnclass = "sf") %>%
filter(continent == "Europe", iso_a2 != "RU") %>%
st_crop(xmin = -24, xmax = 40, ymin = 33, ymax = 74)
绘制欧洲地图
ggplot() +
geom_sf(data=map, color="lightblue1", fill="forestgreen") +
theme_niwot()
获取国家名称
points <- map %>% st_point_on_surface() %>% st_coordinates() %>% as_tibble() %>%
mutate(country=map$name_long)
地图添加文本
ggplot(points) +
geom_sf(data=map, color="lightblue1", fill="forestgreen") +
geom_point(aes(x=X, y=Y)) +
geom_text(aes(x=X, y=Y,label=country),hjust=0, nudge_x=1, check_overlap=TRUE) +
theme_niwot()
❝到此地图就已经绘制完毕,接下来我们通过「ggbump」包来绘制凹凸图来对地图进行数据注释
❞
数据清洗
forest_area <- read_csv("data.txt") %>% filter(year == 2020) %>%
mutate(forest_ha = 4200000000 * (forest_area/100) / 1000000) %>%
select(entity, forest_ha)
line_data <-
points %>% left_join(forest_area, by=c("country" = "entity")) %>%
slice_max(forest_ha, n=15) %>%
mutate(col_y = rank(forest_ha) %>% data_rescale(to=c(40, 70)),sigmoid_end = 52,
col_x_start = 55,col_x_end = forest_ha %>% data_rescale(to=c(55, 130),range = c(0, max(forest_ha))),
area_label = paste0(round(forest_ha, 1), " million ha"))
图形整合
line_data %>% ggplot() +
geom_sf(data=map, color="lightblue1", fill="forestgreen") +
geom_point(aes(x=X, y=Y, color=forest_ha)) +
geom_sigmoid(aes(x=X, y=Y, xend=sigmoid_end, yend=col_y, group=country, color=forest_ha)) +
geom_text(aes(label=country, x=sigmoid_end, y=col_y),hjust=1, size=2, vjust=0, nudge_y = 0.5, alpha=0.8) +
geom_segment(aes(x=col_x_start, xend=col_x_end, y=col_y, yend=col_y, color=forest_ha),size=3) +
geom_text(aes(label=area_label, x=col_x_end, y=col_y), hjust=0, size=2.2, nudge_x = .3) +
coord_sf(clip = "off") +
theme_niwot()
数据获取
❝好了今天的介绍到此结束,需要获取数据的小伙伴可以转发此文到朋友圈公众号后台截图发我,会发送给您数据&代码,感谢各位的支持
❞
欢迎大家扫描下方二位码加入「QQ交流群」,与全国各地上千位小伙伴交流
「关注下方公众号下回更新不迷路」添加作者微信请备注单位+方向+姓名即可
2022-02-11
2022-02-07
2022-02-06
2022-01-28
2022-01-26
2022-01-25
2022-01-24