zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

R可视化:动态热力地图

2023-03-07 09:12:27 时间

本系列内容来自github上面超级火爆的R语言可视化项目:tidyTuesday。是学习R语言数据分析和可视化极好的素材。

  • CSDN项目地址:数绘小站的博客_CSDN博客-Tidy Tuesday[1]

我只是搬运工,感谢小伙伴的分享。


Tidy Tuesday 在 GitHub 上的传送地址:Thomas Mock (2022). Tidy Tuesday: A weekly data project aimed at the R ecosystem. https://github.com/rfordatascience/tidytuesday

在这里插入图片描述

在这里插入图片描述

1. 一些环境设置

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

2. 设置工作路径

wkdir <- '/home/user/R_workdir/TidyTuesday/2018/2018-04-02_US_Tuition_Costs/src-e'
setwd(wkdir)

一些关于字体的设置可以参考这篇文章 R/ggplot2保存图片中文字体至PDF——showtext包一文清除所有障碍 。需要更多的相关字体设置知识可以自行学习帮助文档或检索其他文章,这里不多加累述了。

3. 加载 R 包

library(ggtext)
library(tidyverse)
library(gganimate)
library(transformr)
library(fiftystater)
# 需要能访问 Google, 也可以注释掉下面这行, 影响不大
sysfonts::font_add_google("Gochi Hand", "gochi")

4. 加载数据

df_input <- readxl::read_excel("../data/us_avg_tuition.xlsx")

# 简要查看数据内容
glimpse(df_input)

## Rows: 50
## Columns: 13
## $ State     <chr> "Alabama", "Alaska", "Arizona", "Arkansas", "Caalbert", "C…
## $ `2004-05` <dbl> 5682.838, 4328.281, 5138.495, 5772.302, 5285.921, 4703.777, …
## $ `2005-06` <dbl> 5840.550, 4632.623, 5415.516, 6082.379, 5527.881, 5406.967, …
## $ `2006-07` <dbl> 5753.496, 4918.501, 5481.419, 6231.977, 5334.826, 5596.348, …
## $ `2007-08` <dbl> 6008.169, 5069.822, 5681.638, 6414.900, 5672.472, 6227.002, …
## $ `2008-09` <dbl> 6475.092, 5075.482, 6058.464, 6416.503, 5897.888, 6284.137, …
## $ `2009-10` <dbl> 7188.954, 5454.607, 7263.204, 6627.092, 7258.771, 6948.473, …
## $ `2010-11` <dbl> 8071.134, 5759.153, 8839.605, 6900.912, 8193.739, 7748.201, …
## $ `2011-12` <dbl> 8451.902, 5762.421, 9966.716, 7028.991, 9436.426, 8315.632, …
## $ `2012-13` <dbl> 9098.069, 6026.143, 10133.503, 7286.580, 9360.574, 8792.856,…
## $ `2013-14` <dbl> 9358.929, 6012.445, 10296.200, 7408.495, 9274.193, 9292.954,…
## $ `2014-15` <dbl> 9496.084, 6148.808, 10413.844, 7606.410, 9186.824, 9298.599,…
## $ `2015-16` <dbl> 9751.101, 6571.340, 10646.278, 7867.297, 9269.844, 9748.188,…
# 检查数据的列名
colnames(df_input)
##  [1] "State"   "2004-05" "2005-06" "2006-07" "2007-08" "2008-09" "2009-10"
##  [8] "2010-11" "2011-12" "2012-13" "2013-14" "2014-15" "2015-16"

5. 数据预处理

# 调整年份为 YYYY 格式, 方便绘图展示
df_tidy <- df_input %>%
  dplyr::rename(
    "2004" = "2004-05",
    "2005" = "2005-06",
    "2006" = "2006-07",
    "2007" = "2007-08",
    "2008" = "2008-09",
    "2009" = "2009-10",
    "2010" = "2010-11",
    "2011" = "2011-12",
    "2012" = "2012-13",
    "2013" = "2013-14",
    "2014" = "2014-15",
    "2015" = "2015-16")

# 第一张图片数据预处理
df_tidy.1 <- df_tidy %>%
  # 建议使用 dplyr::mutate 形式调用函数, 有可能与 plyr 中的函数冲突 (因为我自己就报错了...)
  dplyr::mutate(id = tolower(State)) %>%
  dplyr::mutate(cagr = ((`2015`/`2004`)**(1/11)-1)*100) %>%
  select(id, cagr)

# 第二张图片数据预处理
df_tidy.2 <- df_tidy %>%
  dplyr::mutate(id = tolower(State)) %>%
  select(-State) %>%
  gather(key = year, value = cost, -id)


# 简要查看数据内容
glimpse(df_tidy.1)
## Rows: 50
## Columns: 2
## $ id   <chr> "alabama", "alaska", "arizona", "arkansas", "california", "colora…
## $ cagr <dbl> 5.0309094, 3.8688482, 6.8464675, 2.8549355, 5.2391738, 6.8490463,…
glimpse(df_tidy.2)
## Rows: 600
## Columns: 3
## $ id   <chr> "alabama", "alberta", "arizona", "arkansas", "california", "colora…
## $ year <chr> "2004", "2004", "2004", "2004", "2004", "2004", "2004", "2004", "…
## $ cost <dbl> 5682.838, 4328.281, 5138.495, 5772.302, 5285.921, 4703.777, 7983.…

6. 第一张图

6.1 用 ggplot2 开始绘图

# PS: 方便讲解, 我这里进行了拆解, 具体使用时可以组合在一起
gg <- ggplot(df_tidy.1, aes(map_id = id))
# geom_map() 绘制地图
gg <- gg + geom_map(aes(fill = cagr), color = "azure4", map = fifty_states)
# expand_limits() 控制坐标轴的范围
gg <- gg + expand_limits(x = fifty_states$long, y = fifty_states$lat)
# coord_map() 将地图变成球状展示
gg <- gg + coord_map()
# scale_x_continuous() 对连续变量设置坐标轴显示范围
gg <- gg + scale_x_continuous(breaks = NULL)
# scale_y_continuous() 对连续变量设置坐标轴显示范围
gg <- gg + scale_y_continuous(breaks = NULL)
# geom_text() 添加文本信息
gg <- gg + geom_text(x = -68.5, y = 36.5, label = "CAGR (%)", size = 4) 
gg <- gg + ggthemes::theme_fivethirtyeight()
# scale_fill_continuous() 针对连续型数据, 自定义图像的色彩梯度
gg <- gg +scale_fill_continuous(name = "", low = "#00FF00", high = "#FF0000")
# labs() 对图形添加注释和标签(包含标题、子标题、坐标轴和引用等注释)
gg <- gg + labs(title = "从2004年到2016年美国各种学费的年均变化",
                x = NULL,
                y = NULL,
                caption = "资料来源: <i>onlinembapage.com</i> · graph by 萤火之森")
# theme_minimal() 去坐标轴边框的最小化主题
gg <- gg + theme_minimal()
# theme() 实现对非数据元素的调整, 对结果进行进一步渲染, 使之更加美观
gg <- gg + theme(
  # plot.margin 调整图像边距, 上-右-下-左
  plot.margin = grid::unit(c(9, 16, 9, 16), "mm"),
  # aspect.ratio 固定图像的纵横比
  aspect.ratio = 9/16,
  # panel.background 面板背景 数据下面
  panel.background = element_blank(),
  # plot.title 主标题
  plot.title = element_text(hjust = 0.5, size = 32),
  # plot.caption 说明文字
  plot.caption = element_markdown(colour = "dodgerblue4", size = 12),
  # legend.text 设置图例文本格式
  legend.text = element_text(size = 12),
  # legend.title 设置图例标题
  legend.title = element_text(size = 12),
  # legend.position 设置图例位置, 这里用坐标来指定图例的位置
  legend.position = c('.88', '.2'),
  # legend.key.size 调整图例的大小
  legend.key.size = unit(.75, 'cm'),
  # plot.background 图片背景
  plot.background = element_rect(fill = "white"))

6.2 保存图片到 PDF 和 PNG

gg

在这里插入图片描述

filename = '20180402-E-01'
ggsave(filename = paste0(filename, ".pdf"), width = 12.2, height = 7.6, device = cairo_pdf)
ggsave(filename = paste0(filename, ".png"), width = 12.2, height = 7.6, dpi = 100, device = "png")

7. 第二张图

6.1 用 ggplot2 开始绘图

# PS: 方便讲解, 我这里进行了拆解, 具体使用时可以组合在一起
gg <- ggplot(df_tidy.2, aes(frame = year, map_id = id, group = interaction(year, id)))
# geom_map() 绘制地图
gg <- gg + geom_map(aes(fill = cost), color = "azure4", map = fifty_states)
# expand_limits() 控制坐标轴的范围
gg <- gg + expand_limits(x = fifty_states$long, y = fifty_states$lat)
# coord_map() 将地图变成球状展示
gg <- gg + coord_map()
# scale_x_continuous() 对连续变量设置坐标轴显示范围
gg <- gg + scale_x_continuous(breaks = NULL)
# scale_y_continuous() 对连续变量设置坐标轴显示范围
gg <- gg + scale_y_continuous(breaks = NULL, labels = function(x) format(x, big.mark = ".", scientific = FALSE))
# transition_states() 在动画中数据的几个不同阶段之间的转换
gg <- gg + transition_states(year, transition_length = 1, state_length = 4)
# guides() 设置图例信息
gg <- gg + guides(fill = guide_legend(title = "学费及相关的费用"))
# scale_fill_gradientn() 将颜色比例转换为概率转换颜色分布
gg <- gg + scale_fill_gradient(low = "#00FF7F", high = "#DC143C")
gg <- gg + ggthemes::theme_fivethirtyeight() 
# labs() 对图形添加注释和标签(包含标题、子标题、坐标轴和引用等注释)
gg <- gg + labs(title = "美国各州的平均学费:{closest_state} 年",
                subtitle = '',
                x = NULL,
                y = NULL,
                caption = "资料来源: onlinembapage.com · graph by 萤火之森")
# theme_minimal() 去坐标轴边框的最小化主题
gg <- gg + theme_minimal()
# theme() 实现对非数据元素的调整, 对结果进行进一步渲染, 使之更加美观
gg <- gg + theme(
  # panel.grid.major 主网格线, 这一步表示删除主要网格线
  panel.grid.major = element_line("grey", size = 0.2),
  # panel.grid.minor 次网格线, 这一步表示删除次要网格线
  panel.grid.minor = element_blank(),
  # plot.margin 调整图像边距, 上-右-下-左
  plot.margin = grid::unit(c(9, 16, 9, 16), "mm"),
  # aspect.ratio 固定图像的纵横比
  aspect.ratio = 9/16,
  # panel.background 面板背景 数据下面
  panel.background = element_blank(),
  # plot.title 主标题
  plot.title = element_text(family = 'gochi',hjust = 0.5, size = 40),
  # plot.subtitle 次要标题
  plot.subtitle = element_markdown(size = 20),
  # plot.caption 说明文字
  plot.caption = element_markdown(colour = "red", size = 24),
  # legend.text 设置图例文本格式
  legend.text = element_text(family = 'gochi',size = 20),
  # legend.title 设置图例标题
  legend.title = element_text(family = 'gochi',size = 20),
  # legend.position 设置图例位置, 这里用坐标来指定图例的位置
  legend.position = c('.79', '.92'),
  # legend.key.size 调整图例的大小
  legend.key.size = unit(.75, 'cm'),
  # legend.box.background 设置图例背景
  legend.box.background = element_blank(),
  # plot.background 图片背景
  plot.background = element_blank())

7.2 保存图片到 PDF 和 PNG

# 通过调整 duration 参数设置动画长度
animate(gg, renderer = gifski_renderer(), width = 1580, height = 1000, duration = length(unique(df_tidy.2$year)))

在这里插入图片描述

filename = '20180402-E-02'
anim_save(filename = paste0(filename, ".gif"))

测试数据

配套数据下载:us_avg_tuition.xlsx[2]

本次内容来自CSDN,我只是搬运工,项目地址:数绘小站的博客_CSDN博客-Tidy Tuesday[3]

参考资料

[1]CSDN项目地址: https://blog.csdn.net/Albert_XN?type=blog

[2]数据下载: https://gitee.com/tidytuesday/tt-data/blob/master/2018/2018-04-02

[3]CSDN项目地址: https://blog.csdn.net/Albert_XN?type=blog