美文网首页
ggplot2可视化全球人口预期寿命

ggplot2可视化全球人口预期寿命

作者: R语言数据分析指南 | 来源:发表于2021-04-23 23:01 被阅读0次

本节我们通过联合国WPP 2015数据对全球人口预期寿命通过ggplot2来进行数据可视化

加载必须R包

library(tidyverse)
library(magrittr)
library(hrbrthemes)
library(ggdark)
# BiocManager::install("wpp2015")
library(wpp2015)
library(ggridges)
library(patchwork)

导入数据

data(UNlocations)

countries <- UNlocations %>% pull(name) %>% paste

data(e0M)

绘制男性预期寿命

p1 <- e0M %>%
  filter(country %in% countries) %>%
  select(-last.observed) %>%
  gather(period, value, 3:15) %>%
  ggplot(aes(x = value, y = period %>% fct_rev()))+
  geom_density_ridges(aes(fill = period),
  color = "#eaeaea", size = .25)+
  geom_vline(xintercept = 0, color = "#eaeaea")+
  scale_fill_viridis_d(
    option = "mako", begin = .2
  )+
  scale_x_continuous(position = "top", expand = c(0,0))+
  labs(
    x = NULL, y = NULL,
    title = "Global convergence in mortality",
    subtitle = "Male life expectancy at birth"
  )+
  dark_theme_minimal(base_family =  font_rc, base_size = 14)+
  theme(
    legend.position = "none",
    plot.title = element_text(family = "Roboto Slab",
    size = 20, face = 2),
    axis.text = element_text(face = 2),
    plot.background = element_rect(fill = "#222222",color = NA),
    panel.grid.minor.x  = element_blank(),
    panel.grid = element_line(color = "#eaeaea77")
  )

绘制女性预期寿命

data(e0F)

p2 <- e0F %>%
  filter(country %in% countries) %>%
  select(-last.observed) %>%
  gather(period, value, 3:15) %>%
  ggplot(aes(x = value, y = period %>% fct_rev()))+
  geom_density_ridges(aes(fill = period),
  color = "#eaeaea", size = .25)+
  geom_vline(xintercept = 0, color = "#eaeaea")+
  scale_fill_viridis_d(
    option = "rocket", begin = .2
  )+
  scale_x_continuous(position = "top",expand = c(0,0))+
  labs(
    x = NULL, y = NULL,
    subtitle = "Female life expectancy at birth",
    caption = "Data: UN WPP 2015"
  )+
  dark_theme_minimal(base_family =  font_rc, base_size = 14)+
  theme(
    legend.position = "none",
    plot.title = element_text(family = "Roboto Slab",
    size = 20, face = 2),
    axis.text = element_text(face = 2),
    plot.background = element_rect(fill = "#222222", color = NA),
    panel.grid.minor.x  = element_blank(),
    panel.grid = element_line(color = "#eaeaea77")
  )

patchwork进行拼图

p1+p2

通过数据可以看到女性预期寿命远超男性,太难了!

相关文章

网友评论

      本文标题:ggplot2可视化全球人口预期寿命

      本文链接:https://www.haomeiwen.com/subject/hiohrltx.html