20180619-A · Hurricanes & Puerto Rico · ggplot2 geom_ribbon 面积图 分面图 置信区间 画图· R 语言数据可视化 案例 源码

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

2018 年合集传送门: 2018

Hurricanes & Puerto Rico


欢迎来到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-06-19_Hurricanes_Puerto_Rico/src-a'
setwd(wkdir)

3. 加载 R 包

library(lubridate)
library(tidyverse)

# 导入字体设置包
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/week12_mediacloud_hurricanes.csv", show_col_types = FALSE)
df_albert <- readr::read_csv("../data/week12_mediacloud_states.csv", show_col_types = FALSE)

# 简要查看数据内容
glimpse(df_input)
## Rows: 38
## Columns: 5
## $ Date   <chr> "8/20/17", "8/21/17", "8/22/17", "8/23/17", "8/24/17", "8/25/17…
## $ Harvey <dbl> 0, 0, 4, 6, 309, 1348, 995, 960, 1956, 2283, 1603, 1503, 1109, …
## $ Irma   <dbl> 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 61, 66, 36, 52, 221, 793, 1668…
## $ Maria  <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, …
## $ Jose   <dbl> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 31, 93, 167,…
# 检查数据的列名
colnames(df_input)
## [1] "Date"   "Harvey" "Irma"   "Maria"  "Jose"

5. 数据预处理

df_tidy_one <- df_input %>% 
  # select() 选择需要使用的列
  select(-Jose) %>% 
  # mutate() 主要用于在数据框中添加新的变量, 这些变量是通过对现有的变量进行操作而形成的
  dplyr::mutate(Date = mdy(Date)) %>% 
  # gather() 数据收缩、从宽表到长表. key 将原数据框中所有的列赋值给这个变量; value 将原数据框中所有的值赋值给这个变量
  gather(key = "key", value = "value", -Date) %>% 
  dplyr::mutate(type = "飓风/台风", color = key) 

df_tidy_two <- df_albert %>% 
  dplyr::mutate(Date = mdy(Date)) %>%
  # rename() 列重命名
  rename("Puerto Rico" = '"Puerto Rico"') %>% 
  gather(key = "key", value = "value", -Date) %>% 
  dplyr::mutate(type = "城市")%>% 
  dplyr::mutate (color = case_when(key == "Texas" ~ "Harvey",
                                   key == "Florida" ~ "Irma",
                                   key == "Puerto Rico" ~ "Maria"))

# bind_rows() 高效地按行绑定多个数据帧
df_plot <- bind_rows(df_tidy_one, df_tidy_two)

# 简要查看数据内容
glimpse(df_plot)
## Rows: 267
## Columns: 5
## $ Date  <date> 2017-08-20, 2017-08-21, 2017-08-22, 2017-08-23, 2017-08-24, 201…
## $ key   <chr> "Harvey", "Harvey", "Harvey", "Harvey", "Harvey", "Harvey", "Har…
## $ value <dbl> 0, 0, 4, 6, 309, 1348, 995, 960, 1956, 2283, 1603, 1503, 1109, 7…
## $ type  <chr> "飓风/台风", "飓风/台风", "飓风/台风", "飓风/台风", "飓风/台风",…
## $ color <chr> "Harvey", "Harvey", "Harvey", "Harvey", "Harvey", "Harvey", "Har…

6. 利用 ggplot2 绘图

# PS: 方便讲解, 我这里进行了拆解, 具体使用时可以组合在一起
gg <- df_plot %>% ggplot()
# geom_ribbon() 绘制置信区间和面积图
gg <- gg + geom_ribbon(aes(x = Date, ymin = 0, ymax = value, fill = color), color = "#BC8F8F")
# scale_x_date() 格式化日期
gg <- gg + scale_x_date(date_labels = "%b %d",
                        limits = c(as_date("2017-08-20"), as_date("2017-09-24")),
                        breaks = seq(as_date("2017-08-20"), as_date("2017-09-17"), "1 week"))
# scale_y_continuous() 对连续变量设置坐标轴显示范围
gg <- gg + scale_y_continuous(breaks = seq(0, 4000, 1000), labels = seq(0, 4000, 1000))
# scale_fill_manual() 采取的是手动赋值的方法, 也就是直接把颜色序列赋值给它的参数 values, 也可以根据 breaks, labels 设定图例标签顺序
gg <- gg + scale_fill_manual(values = c('#1E90FF', '#FF4500', '#9370DB'))
# facet_wrap() 可视化分面图
gg <- gg + facet_wrap(~ type)
  
# 在各个分面中添加注释文本
txt <- tribble(
    ~x, ~y, ~label, ~type,
    "2017-08-30", 2700, "Harvey", "飓风/台风",
    "2017-09-10", 2700, "Irma", "飓风/台风",
    "2017-09-20", 800, "Maria", "飓风/台风",
    "2017-08-24", 4000, "德克萨斯", "城市",
    "2017-09-06", 3700, "佛罗里达", "城市",
    "2017-09-20", 1700, "波多黎各", "城市")
txt <- mutate(txt, x = as_date(x))

# geom_text() 添加文本信息
gg <- gg + geom_text(data = txt, aes(x = x, y = y, label = label))
# labs() 对图形添加注释和标签(包含标题 title、子标题 subtitle、坐标轴 x & y 和引用 caption 等注释)
gg <- gg + labs(title = "想不到啥标题了, 这个就是标题了",
                x = NULL,
                y = NULL,
                caption = "资料来源: FiveThirtyEight.com · graph by 萤火之森 · 2022-10-20")
# 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.5, color = "black", size = 20, face = "bold", family = 'zxw'),
  # plot.caption 说明文字
  plot.caption =  element_text(hjust = 0.85, vjust = 87, size = 10, color = '#FFA500'),
  # strip.text.x 自定义分面图每个分面标题的文字
  strip.text.x = element_text(size = 24, hjust = 0, face = "bold", family = 'zxw', color = 'red'),
  # axis.text 坐标轴刻度文本
  axis.text = element_text(size = 12, hjust = 0, face = "bold", color = '#FFA500', family = 'albert'),
  # legend.position 设置图例位置, "none" 表示不显示图例
  legend.position = 'none')

7. 保存图片到 PDF 和 PNG

gg

在这里插入图片描述

filename = '20180619-A-01'
ggsave(filename = paste0(filename, ".pdf"), width = 9.2, height = 7.5, device = cairo_pdf)
ggsave(filename = paste0(filename, ".png"), width = 9.2, height = 7.5, dpi = 100, device = "png", bg = 'white')

8. 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  forcats_0.5.2  
##  [5] stringr_1.4.1   dplyr_1.0.10    purrr_0.3.4     readr_2.1.2    
##  [9] tidyr_1.2.1     tibble_3.1.8    ggplot2_3.3.6   tidyverse_1.3.2
## [13] lubridate_1.8.0
## 
## loaded via a namespace (and not attached):
##  [1] assertthat_0.2.1    digest_0.6.29       utf8_1.2.2         
##  [4] R6_2.5.1            cellranger_1.1.0    backports_1.4.1    
##  [7] reprex_2.0.2        evaluate_0.16       highr_0.9          
## [10] httr_1.4.4          pillar_1.8.1        rlang_1.0.6        
## [13] curl_4.3.3          googlesheets4_1.0.1 readxl_1.4.1       
## [16] rstudioapi_0.14     jquerylib_0.1.4     rmarkdown_2.16     
## [19] textshaping_0.3.6   googledrive_2.0.0   bit_4.0.4          
## [22] munsell_0.5.0       broom_1.0.1         compiler_4.2.1     
## [25] modelr_0.1.9        xfun_0.32           systemfonts_1.0.4  
## [28] pkgconfig_2.0.3     htmltools_0.5.3     tidyselect_1.1.2   
## [31] fansi_1.0.3         crayon_1.5.2        tzdb_0.3.0         
## [34] dbplyr_2.2.1        withr_2.5.0         grid_4.2.1         
## [37] jsonlite_1.8.2      gtable_0.3.1        lifecycle_1.0.3    
## [40] DBI_1.1.3           magrittr_2.0.3      scales_1.2.1       
## [43] vroom_1.5.7         cli_3.4.1           stringi_1.7.8      
## [46] cachem_1.0.6        farver_2.1.1        fs_1.5.2           
## [49] xml2_1.3.3          bslib_0.4.0         ragg_1.2.3         
## [52] ellipsis_0.3.2      generics_0.1.3      vctrs_0.4.2        
## [55] tools_4.2.1         bit64_4.0.5         glue_1.6.2         
## [58] hms_1.1.2           parallel_4.2.1      fastmap_1.1.0      
## [61] yaml_2.3.5          colorspace_2.0-3    gargle_1.2.1       
## [64] rvest_1.0.3         knitr_1.40          haven_2.5.1        
## [67] sass_0.4.2

测试数据

配套数据下载:Hurricanes & Puerto Rico

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值