20180703-A · Global Life Expectancy · ggplot2 gganimate 世界地图 动态地图 geom_sf 画图 动图 · R 语言数据可视化 案例 源码

本文展示了如何使用ggplot2和gganimate绘制全球生命期望数据的静态和动态地图,通过gganimate呈现了1950年至2015年间各国平均寿命的变化趋势,借助scico调色板和世界地图数据,揭示了不同时期的全球健康状况。
摘要由CSDN通过智能技术生成

所有作品合集传送门: Tidy Tuesday

2018 年合集传送门: 2018

Global Life Expectancy


欢迎来到ggplot2的世界!

ggplot2是一个用来绘制统计图形的 R 软件包。它可以绘制出很多精美的图形,同时能避免诸多的繁琐细节,例如添加图例等。

用 ggplot2 绘制图形时,图形的每个部分可以依次进行构建,之后还可以进行编辑。ggplot2 精心挑选了一系列的预设图形,因此在大部分情形下可以快速地绘制出许多高质量的图形。如果在格式上还有额外的需求,也可以利用 ggplot2 中的主题系统来进行定制, 无需花费太多时间来调整图形的外观,而可以更加专注地用图形来展现你的数据。


在这里插入图片描述
在这里插入图片描述

1. 一些环境设置

# 设置为国内镜像, 方便快速安装模块
options("repos" = c(CRAN = "https://mirrors.tuna.tsinghua.edu.cn/CRAN/"))

2. 设置工作路径

wkdir <- '/home/user/R_workdir/TidyTuesday/2018/2018-07-03_Global_Life_Expectancy/src-a'
setwd(wkdir)

3. 加载 R 包

# 本示例中的 gganimate 包需要安装 v0.1.1 版本, 否则会提示以下报错
# Error: It appears that you are trying to use the old API, which has been deprecated.
# Please update your code to the new API or install the old version of gganimate
# from https://github.com/thomasp85/gganimate/releases/tag/v0.1.1
# devtools::install_github("thomasp85/gganimate", ref = "v0.1.1", force = TRUE)

library(sf)
library(glue)
library(scico)
library(animation)
library(gganimate)
library(tidyverse)
library(hrbrthemes)

# 导入字体设置包
library(showtext)
# font_add_google() showtext 中从谷歌字体下载并导入字体的函数
# name 中的是字体名称, 用于检索, 必须严格对应想要字体的名字 
# family 后面的是代码后面引用时的名称, 自己随便起
# 需要能访问 Google, 也可以注释掉下面这行, 影响不大
# font_families_google() 列出所有支持的字体, 支持的汉字不多
# http://www.googlefonts.net/
font_add_google(name = "Karantina", family =  "ka")
font_add_google(name = "Cutive", family = "albert")
font_add_google(name = "ZCOOL XiaoWei", family = "zxw")

# 后面字体均可以使用导入的字体
showtext_auto()

4. 加载数据

df_input <- readr::read_csv("../data/week14_global_life_expectancy.csv", show_col_types = FALSE)

# 简要查看数据内容
glimpse(df_input)
## Rows: 17,894
## Columns: 4
## $ country         <chr> "Afghanistan", "Afghanistan", "Afghanistan", "Afghanis…
## $ code            <chr> "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG"…
## $ year            <dbl> 1950, 1951, 1952, 1953, 1954, 1955, 1956, 1957, 1958, …
## $ life_expectancy <dbl> 27.537, 27.810, 28.350, 28.880, 29.399, 29.907, 30.404…
# 检查数据的列名
colnames(df_input)
## [1] "country"         "code"            "year"            "life_expectancy"

5. 数据预处理

# rnaturalearth::ne_download() 从 Natural Earth 下载数据并(load = TRUE)读入 R
worldmap <- rnaturalearth::ne_download(scale = 110,
                                       category = "cultural",
                                       type = "countries",
                                       load = TRUE,
                                       destdir = tempdir(),
                                       returnclass = "sf") %>% 
  # select() 选择需要使用的列
  select(SOVEREIGNT, SOV_A3, ADMIN, ADM0_A3, geometry)

df_albert <- df_input %>% 
  # filter() 根据条件过滤数据, 这里过滤 code 缺失值的观测
  filter(!is.na(code)) %>% 
  # left_join() 左连接 worldmap
  left_join(worldmap, by = c("code" = "ADM0_A3"))

6. 利用 ggplot2 绘图

6.1 静态地图

# 这里挑选 2012 年的数据
spec.year <- 2012

# PS: 方便讲解, 我这里进行了拆解, 具体使用时可以组合在一起
gg <- df_albert %>% filter(year == spec.year) %>% ggplot()
# geom_sf() 绘制地图
gg <- gg + geom_sf(aes(fill = life_expectancy, geometry = `geometry`))
# scico::scale_fill_scico() 针对连续型数据, 自定义图像的色彩梯度, scico::scico_palette_names() 可以查看所有支持的 palette 名称
gg <- gg + scale_fill_scico(palette = "roma", na.value = "#A9A9A9", limits = c(50, 90),
                            breaks = c(50, 60, 70, 80, 90), 
                            labels = c(50, 60, 70, 80, 90))
# guides() 设置图例信息
gg <- gg + guides(fill = guide_legend(title = '平均寿命/年',
                                      frame.color = "white",
                                      ticks.colour = "red",
                                      title.position = "top",
                                      label.position = "bottom",
                                      nrow = 1, byrow = TRUE))
# labs() 对图形添加注释和标签(包含标题 title、子标题 subtitle、坐标轴 x & y 和引用 caption 等注释)
gg <- gg + labs(title = glue("平均寿命, {spec.year}"),
                subtitle = '人口平均预期寿命的计算要用到一连串的数学公式。如果用文字来描述,则计算人口平均预期寿命的方法就是:对同时出生的一批人进行追踪调查,\n分别记下他们在各年龄段的死亡人数直至最后一个人的寿命结束,然后根据这一批人活到各种不同年龄的人数来计算人口的平均寿命。',
                x = NULL,
                y = NULL,
                caption = "资料来源: ourworldindata.org · graph by 数绘小站 · 2022-10-21")
# theme_minimal() 去坐标轴边框的最小化主题
gg <- gg + theme_minimal()
# theme() 实现对非数据元素的调整, 对结果进行进一步渲染, 使之更加美观
gg <- gg + theme(
  # panel.background 面板背景 数据下面
  panel.background = element_blank(),
  # plot.background 图片背景 
  plot.background = element_blank(),
  # plot.margin 调整图像边距, 上-右-下-左
  plot.margin = margin(12, 10, -2, 15), 
  # plot.title 主标题
  plot.title = element_text(hjust = 0, color = "black", size = 20, face = "bold", family = 'zxw'),
  # plot.subtitle 次要标题
  plot.subtitle = element_text(size = 10.5, family = 'zxw'),
  # plot.caption 说明文字
  plot.caption =  element_text(hjust = 0.85, vjust = -0.5, size = 10),
  # axis.text 坐标轴刻度文本
  axis.text = element_text(size = 12, hjust = 0, face = "bold", color = '#FFA500', family = 'albert'),
  # legend.direction 设置图例的方向, vertical 表示垂直摆放图例; horizontal 表示水平摆放图例
  legend.direction = 'horizontal',
  # legend.position 设置图例位置, 这里指定图例具体的摆放位置
  legend.position = c(0.12, 0.2))

filename = '20180703-A-01'
ggsave(filename = paste0(filename, ".pdf"), width = 12, height = 6.0, device = cairo_pdf)
ggsave(filename = paste0(filename, ".png"), width = 12, height = 6.0, dpi = 100, device = "png", bg = 'white')

gg

在这里插入图片描述

6.2 动态地图

# PS: 方便讲解, 我这里进行了拆解, 具体使用时可以组合在一起
hh <- df_albert %>% filter(year %in% seq(1950, 2015, 5)) %>% ggplot(aes(frame = year))
# stat_sf requires the following missing aesthetics: geometry
hh <- hh + geom_sf(aes(fill = life_expectancy, geometry = `geometry`))
# geom_sf() 绘制地图
hh <- hh + geom_sf(aes(fill = life_expectancy, geometry = `geometry`))
# scico::scale_fill_scico() 针对连续型数据, 自定义图像的色彩梯度, scico::scico_palette_names() 可以查看所有支持的 palette 名称
hh <- hh + scale_fill_scico(palette = "roma", na.value = "#A9A9A9", limits = c(50, 90),
                            breaks = c(50, 60, 70, 80, 90), 
                            labels = c(50, 60, 70, 80, 90))
# guides() 设置图例信息
hh <- hh + guides(fill = guide_legend(title = '平均寿命/年',
                                      frame.color = "white",
                                      ticks.colour = "red",
                                      title.position = "top",
                                      label.position = "bottom",
                                      nrow = 1, byrow = TRUE))
# labs() 对图形添加注释和标签(包含标题 title、子标题 subtitle、坐标轴 x & y 和引用 caption 等注释)
hh <- hh + labs(title = glue("平均寿命, {spec.year}"),
                subtitle = '人口平均预期寿命的计算要用到一连串的数学公式。如果用文字来描述,则计算人口平均预期寿命的方法就是:对同时出生的一批人进行追踪调查,\n分别记下他们在各年龄段的死亡人数直至最后一个人的寿命结束,然后根据这一批人活到各种不同年龄的人数来计算人口的平均寿命。',
                x = NULL,
                y = NULL,
                caption = "资料来源: ourworldindata.org · graph by 数绘小站 · 2022-10-21")
# theme_minimal() 去坐标轴边框的最小化主题
hh <- hh + theme_minimal()
# theme() 实现对非数据元素的调整, 对结果进行进一步渲染, 使之更加美观
hh <- hh + theme(
  # panel.background 面板背景 数据下面
  panel.background = element_blank(),
  # plot.background 图片背景 
  plot.background = element_blank(),
  # plot.margin 调整图像边距, 上-右-下-左
  plot.margin = margin(12, 10, -2, 15), 
  # plot.title 主标题
  plot.title = element_text(hjust = 0, color = "black", size = 20, face = "bold", family = 'zxw'),
  # plot.subtitle 次要标题
  plot.subtitle = element_text(size = 10.5, family = 'zxw'),
  # plot.caption 说明文字
  plot.caption =  element_text(hjust = 0.85, vjust = -0.5, size = 10),
  # axis.text 坐标轴刻度文本
  axis.text = element_text(size = 12, hjust = 0, face = "bold", color = '#FFA500', family = 'albert'),
  # legend.direction 设置图例的方向, vertical 表示垂直摆放图例; horizontal 表示水平摆放图例
  legend.direction = 'horizontal',
  # legend.position 设置图例位置, 这里指定图例具体的摆放位置
  legend.position = c(0.12, 0.2))

# 设置动图的间隔
animation::ani.options(interval = 1)
# gganimate::gganimate() 构建基于 GIF 的动图
gganimate::gganimate(hh, "20180703-A-02.gif", title_frame = TRUE, ani.width = 1200, ani.height = 600)

在这里插入图片描述

7. session-info

sessionInfo()
## R version 4.2.1 (2022-06-23)
## Platform: x86_64-pc-linux-gnu (64-bit)
## Running under: Ubuntu 20.04.5 LTS
## 
## Matrix products: default
## BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3
## LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/liblapack.so.3
## 
## locale:
##  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
##  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
##  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
##  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
##  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
## [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] showtext_0.9-5   showtextdb_3.0   sysfonts_0.8.8   hrbrthemes_0.8.0
##  [5] forcats_0.5.2    stringr_1.4.1    dplyr_1.0.10     purrr_0.3.4     
##  [9] readr_2.1.2      tidyr_1.2.1      tibble_3.1.8     ggplot2_3.3.6   
## [13] tidyverse_1.3.2  gganimate_0.1.1  animation_2.7    scico_1.3.1     
## [17] glue_1.6.2       sf_1.0-8        
## 
## loaded via a namespace (and not attached):
##  [1] fs_1.5.2            lubridate_1.8.0     bit64_4.0.5        
##  [4] httr_1.4.4          tools_4.2.1         backports_1.4.1    
##  [7] bslib_0.4.0         utf8_1.2.2          rgdal_1.5-32       
## [10] R6_2.5.1            KernSmooth_2.23-20  DBI_1.1.3          
## [13] colorspace_2.0-3    withr_2.5.0         sp_1.5-0           
## [16] tidyselect_1.1.2    bit_4.0.4           curl_4.3.3         
## [19] compiler_4.2.1      extrafontdb_1.0     textshaping_0.3.6  
## [22] cli_3.4.1           rvest_1.0.3         xml2_1.3.3         
## [25] sass_0.4.2          scales_1.2.1        classInt_0.4-8     
## [28] proxy_0.4-27        systemfonts_1.0.4   digest_0.6.30      
## [31] rmarkdown_2.16      base64enc_0.1-3     pkgconfig_2.0.3    
## [34] htmltools_0.5.3     extrafont_0.18      highr_0.9          
## [37] dbplyr_2.2.1        fastmap_1.1.0       rlang_1.0.6        
## [40] readxl_1.4.1        rstudioapi_0.14     farver_2.1.1       
## [43] jquerylib_0.1.4     generics_0.1.3      jsonlite_1.8.2     
## [46] vroom_1.5.7         googlesheets4_1.0.1 magrittr_2.0.3     
## [49] s2_1.1.0            Rcpp_1.0.9          munsell_0.5.0      
## [52] fansi_1.0.3         gdtools_0.2.4       lifecycle_1.0.3    
## [55] stringi_1.7.8       yaml_2.3.5          plyr_1.8.7         
## [58] grid_4.2.1          parallel_4.2.1      crayon_1.5.2       
## [61] lattice_0.20-45     haven_2.5.1         hms_1.1.2          
## [64] magick_2.7.3        knitr_1.40          pillar_1.8.1       
## [67] wk_0.7.0            reprex_2.0.2        evaluate_0.16      
## [70] modelr_0.1.9        vctrs_0.4.2         tzdb_0.3.0         
## [73] Rttf2pt1_1.3.10     cellranger_1.1.0    gtable_0.3.1       
## [76] assertthat_0.2.1    cachem_1.0.6        xfun_0.32          
## [79] broom_1.0.1         e1071_1.7-11        rnaturalearth_0.1.0
## [82] ragg_1.2.3          class_7.3-20        googledrive_2.0.0  
## [85] gargle_1.2.1        units_0.8-0         ellipsis_0.3.2

测试数据

配套数据下载:Global Life Expectancy

好的,以下是一个Python+pandas+matplotlib的数据分析与可视化案例。 这个案例涉及到一个名为"World Happiness Report"的数据集,该数据集包含了157个国家的幸福指数及其对应的各项因素数据,例如经济、社会、健康等。 首先,我们需要导入相关的库和数据集: ```python import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('world_happiness_report.csv') ``` 接下来,我们可以先看一下数据集的基本信息: ```python print(df.head()) print(df.info()) ``` 然后,我们可以通过绘制柱状图来比较不同国家的幸福指数: ```python plt.figure(figsize=(15, 10)) plt.bar(df['Country'], df['Happiness Score']) plt.xticks(rotation=90) plt.title('World Happiness Report') plt.xlabel('Country') plt.ylabel('Happiness Score') plt.show() ``` 接着,我们可以通过散点图来探究幸福指数与经济因素之间的关系: ```python plt.figure(figsize=(10, 8)) plt.scatter(df['Economy (GDP per Capita)'], df['Happiness Score']) plt.title('Happiness Score vs. GDP per Capita') plt.xlabel('Economy (GDP per Capita)') plt.ylabel('Happiness Score') plt.show() ``` 最后,我们可以通过热图来展示不同因素对幸福指数的影响情况: ```python factors = ['Economy (GDP per Capita)', 'Family', 'Health (Life Expectancy)', 'Freedom', 'Trust (Government Corruption)', 'Generosity'] corr_matrix = df[factors].corr() plt.figure(figsize=(10, 8)) plt.imshow(corr_matrix, cmap='coolwarm', interpolation='none') plt.colorbar() plt.xticks(range(len(factors)), factors, rotation=90) plt.yticks(range(len(factors)), factors) plt.title('Correlation Matrix') plt.show() ``` 以上就是一个简单的Python+pandas+matplotlib数据分析与可视化案例,希望对你有帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值