加载R包
代码语言:javascript
复制library(tidyverse)
library(sf)
library(camcorder)
library(MetBrewer)
# install.packages("giscoR")
library(giscoR)
R包版本
导入数据
代码语言:javascript
复制life_df <- read_csv('data.csv') %>% janitor::clean_names()
数据清洗
代码语言:javascript
复制le_change <- life_df %>%
group_by(entity) %>%
filter(year == 2021 | year ==1995) %>%
filter(!is.na(code)) %>%
pivot_wider(names_from = year, values_from = c(life_expectancy0,
life_expectancy10,
life_expectancy25,
life_expectancy45,
life_expectancy65,
life_expectancy80)) %>%
pivot_longer(`Life expectancy at age 0`:`At age 80`, names_to = "age", values_to = "change") %>%
mutate(age = fct_inorder(age))
获取地图数据
代码语言:javascript
复制world <- giscoR::gisco_get_countries() %>%
janitor::clean_names() %>%
rename(code = iso3_code) %>%
st_transform(crs = " proj=moll")
world_le_2021 <- world %>% left_join(le_change) %>%
filter(!is.na(change))
数据可视化
代码语言:javascript
复制ggplot(world_le_2021)
geom_sf(aes(fill = change), linewidth = 0.05, color = "black")
scale_fill_gradientn(colors=rev(met.brewer("Cassatt1")))
facet_wrap(vars(age), ncol = 2)
guides(fill = guide_colorsteps(title.position = "top", show.limits = TRUE))
theme_minimal()
theme(
legend.position = "top",
legend.title = element_text(hjust = 0.5),
legend.key.width = unit(3, "lines"),
legend.key.height = unit(0.6, "lines"),
plot.background = element_rect(fill = "grey99", color = NA),
strip.text = element_text(size = 12),
axis.text = element_blank(),
panel.grid = element_line(linewidth = 0.1, color = "grey70"),
plot.margin = margin(10, 10, 10, 10))