本文主要是介绍20180521-A · US Honey Production · ggplot2 dplyr ggdraw geom_bar magick 柱状图 条形图 · R 语言数据可视化 案例 源码,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
所有作品合集传送门: Tidy Tuesday
2018 年合集传送门: 2018
US Honey Production
欢迎来到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-05-21_US_Honey_Production/src-a'
setwd(wkdir)
3. 加载 R 包
library(cowplot)
library(tidyverse)# 导入字体设置包
library(showtext) # font_add_google() showtext 中从谷歌字体下载并导入字体的函数
# name 中的是字体名称, 用于检索, 必须严格对应想要字体的名字
# family 后面的是代码后面引用时的名称, 自己随便起
# 需要能访问 Google, 也可以注释掉下面这行, 影响不大
# font_families_google() 列出所有支持的字体, 支持的汉字不多
# http://www.googlefonts.net/
font_add_google(name = "Gochi Hand", family = "gochi")
font_add_google(name = "Staatliches" , family = "staat")
font_add_google(name = "ZCOOL QingKe HuangYou", family = "zqhy")# 后面字体均可以使用导入的字体
showtext_auto()
4. 加载数据
# 加载原始数据. 注: 原始数据结构比较复杂, 可以自行查看
df_input_a <- readr::read_csv('../data/honeyraw_1998to2002.csv', col_names = FALSE, skip = 9)
df_input_b <- readr::read_csv('../data/honeyraw_2003to2007.csv', col_names = FALSE, skip = 81)
df_input_c <- readr::read_csv('../data/honeyraw_2008to2012.csv', col_names = FALSE, skip = 72)# 简要查看数据内容
glimpse(df_input_a)
## Rows: 288
## Columns: 9
## $ X1 <dbl> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
## $ X2 <chr> "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d", "d…
## $ X3 <chr> "AL", "AZ", "AR", "CA", "CO", "FL", "GA", "HI", "ID", "IL", "IN", "…
## $ X4 <chr> "16", "55", "53", "450", "27", "230", "75", "8", "120", "9", "9", "…
## $ X5 <chr> "71", "60", "65", "83", "72", "98", "56", "118", "50", "71", "92", …
## $ X6 <chr> "1136", "3300", "3445", "37350", "1944", "22540", "4200", "944", "6…
## $ X7 <chr> "159", "1485", "1688", "12326", "1594", "4508", "307", "66", "2220"…
## $ X8 <chr> "72", "64", "59", "62", "70", "64", "69", "77", "65", "119", "85", …
## $ X9 <chr> "818", "2112", "2033", "23157", "1361", "14426", "2898", "727", "39…
# 检查数据的列名
colnames(df_input_a)
## [1] "X1" "X2" "X3" "X4" "X5" "X6" "X7" "X8" "X9"
5. 数据预处理
# 自定义函数
mytidy <- function(df_input, y){df_input %>% # 去除缺失值drop_na()%>% # datasets::state.abb 数据集存放了美国各州的英文缩写名, 这一步用于筛选美国各州的数据filter(X3 %in% state.abb) %>% # mutate_at() 通过名称修改指定数据列的内容dplyr::mutate_at(vars(X4:X9), as.numeric) %>% # mutate() 主要用于在数据框中添加新的变量, 这些变量是通过对现有的变量进行操作而形成的dplyr::mutate(X1 = X1 + y -1,X4 = X4 * 1000,X6 = X4 * X5,X7 = X7 * 1000,X8 = X8/100,X9 = X6 * X8) %>% # select() 筛选需要的列, - 表示剔除指定的列select(-X2) %>% # rename() 为了便于后续理解, 重命名指定的列rename(year = X1, st = X3,numcol = X4,yieldpercol = X5,totalprod = X6,stocks = X7,priceperlb = X8, prodvalue = X9)
}# 通过自定义函数, 进一步整理数据
df_tidy_a <- mytidy(df_input_a, 1998)
df_tidy_b <- mytidy(df_input_b, 2003)
df_tidy_c <- df_input_c %>% # 因为 df_input_c$X3 为美国各州的英文缩写, 这里将其替换成全名, 以兼容自定义函数mutate(X3 = state.abb[match(X3, state.name)]) %>% mytidy(2008)# 按行合并三个数据集
df_plot <- dplyr::bind_rows(df_tidy_a, df_tidy_b, df_tidy_c)# 简要查看数据内容
glimpse(df_plot)
## Rows: 626
## Columns: 8
## $ year <dbl> 1998, 1998, 1998, 1998, 1998, 1998, 1998, 1998, 1998, 1998…
## $ st <chr> "AL", "AZ", "AR", "CA", "CO", "FL", "GA", "HI", "ID", "IL"…
## $ numcol <dbl> 16000, 55000, 53000, 450000, 27000, 230000, 75000, 8000, 1…
## $ yieldpercol <dbl> 71, 60, 65, 83, 72, 98, 56, 118, 50, 71, 92, 78, 46, 50, 1…
## $ totalprod <dbl> 1136000, 3300000, 3445000, 37350000, 1944000, 22540000, 42…
## $ stocks <dbl> 159000, 1485000, 1688000, 12326000, 1594000, 4508000, 3070…
## $ priceperlb <dbl> 0.72, 0.64, 0.59, 0.62, 0.70, 0.64, 0.69, 0.77, 0.65, 1.19…
## $ prodvalue <dbl> 817920, 2112000, 2032550, 23157000, 1360800, 14425600, 289…
6. 利用 ggplot2 绘图
# 加载一个本地图片
bee.img <- magick::image_read('../data/bee.jpg') %>%magick::image_colorize(opacity = 28, color = 'white')# PS: 方便讲解, 我这里进行了拆解, 具体使用时可以组合在一起
gg <- df_plot %>%# 根据 st 州名将数据进行分组group_by(st) %>% # summarise() 总结指定的列, 这里求和summarise(sumprod = sum(totalprod)) %>% # arrange() + desc() 降序排列arrange(desc(sumprod)) %>% # 新建 ggplot2 画布ggplot(aes(x = fct_reorder(st, sumprod), y = sumprod))
# geom_bar() 绘制条形图, stat = "identity",意味着条形的高度表示数据数据的值
gg <- gg + geom_bar(stat = "identity")
# coord_flip() 横纵坐标位置转换
gg <- gg + coord_flip()
# geom_text() 添加文本信息, 同时格式化输出大位数字
gg <- gg + geom_text(aes(st, sumprod, label = format(sumprod, big.mark = ",", scientific = FALSE)), hjust = -0.02, colour = 'red', family = 'gochi')
# scale_y_continuous() 对连续变量设置坐标轴显示范围
# scales::unit_format() 通过添加单位后缀来优化缩放比例, 这里以 Million 百万来缩放
gg <- gg + scale_y_continuous(labels = scales::unit_format(unit = "M", scale = 1e-6), limits = c(0, 510000000))
# labs() 对图形添加注释和标签(包含标题 title、子标题 subtitle、坐标轴 x & y 和引用 caption 等注释)
gg <- gg + labs(title = "美国蜂蜜生产 (1998-2012)",subtitle = NULL,x = NULL,y = NULL,caption = "资料来源: Bee Culture - graph by 数绘小站")
# theme_minimal() 去坐标轴边框的最小化主题
gg <- gg + theme_minimal()
# theme() 实现对非数据元素的调整, 对结果进行进一步渲染, 使之更加美观
gg <- gg + theme(# panel.grid.major 主网格线, 这一步表示删除主要网格线panel.grid.major = element_blank(),# panel.grid.minor 次网格线, 这一步表示删除次要网格线panel.grid.minor = element_blank(),# panel.border 面板背景 数据上面panel.border = element_blank(),# panel.background 面板背景 数据下面panel.background = element_blank(),# plot.margin 调整图像边距, 上-右-下-左plot.margin = margin(12, 15, 2, 10), # axis.text.x X-坐标轴文本axis.text.x = element_text(size = 11),# axis.text.y Y-坐标轴文本, 这里调整坐标轴标签与坐标轴之间的间距axis.text.y = element_text(size = 12, margin = margin(0, -1, 0, 0, 'cm')),# text 设置文本格式text = element_text(family = 'staat'),# plot.background 图片背景plot.background = element_blank(),# plot.title 主标题plot.title = element_text(hjust = 0.1, color = "black", size = 32, face = "bold", family = 'zqhy'),# plot.caption 说明文字plot.caption = element_text(size = 16, hjust = 0.85, vjust = 50, family = 'zqhy'),# legend.position 设置图例位置, "none" 表示不显示图例legend.position = "none")# 利用 cowplot::ggdraw 合并多个图
info.text = '2016年,美国拥有5个或更多蜂群的生产商生产的\n蜂蜜总量为1.619亿磅,比2015年增长了3%。2016\n年,采集蜂蜜的蜂群有278万个,比2015年增长了\n4%。每个蜂群收获的蜂蜜平均产量为58.3磅,比\n2015年的58.9磅下降了1%。'
source.text = '数据来源: Bee Culture · 2016'
caption.text = 'GRAPH BY 数绘小站'
merge.gg <- ggdraw()
merge.gg <- merge.gg + draw_image(bee.img, x = -0.05, y = -0.21, height = 1.42, width = 1.22)
merge.gg <- merge.gg + draw_plot(gg, x = 0., y = -0.04, height = 1.05, width = 1.02)
merge.gg <- merge.gg + draw_text(text = info.text, x = 0.305, y = 0.55 , family = "zqhy" , size = 15 , hjust = 0)
merge.gg <- merge.gg + draw_text(text = source.text, x = 0.385, y = 0.325, size = 16 , hjust = 0)
merge.gg <- merge.gg + draw_text(text = caption.text, x = 0.685, y = 0.325 , color = 'red' , size = 16 , hjust = 0)
7. 保存图片到 PDF 和 PNG
gg
filename = '20180521-A-01'
ggsave(filename = paste0(filename, ".pdf"), width = 9.6, height = 6.4, device = cairo_pdf)
ggsave(filename = paste0(filename, ".png"), width = 9.6, height = 6.4, dpi = 100, device = "png", bg = 'white')
merge.gg
filename = '20180521-A-02'
ggsave(filename = paste0(filename, ".pdf"), width = 9.6, height = 6.1, device = cairo_pdf)
ggsave(filename = paste0(filename, ".png"), width = 9.6, height = 6.1, 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] cowplot_1.1.1
##
## loaded via a namespace (and not attached):
## [1] httr_1.4.4 sass_0.4.2 bit64_4.0.5
## [4] vroom_1.5.7 jsonlite_1.8.2 modelr_0.1.9
## [7] bslib_0.4.0 assertthat_0.2.1 highr_0.9
## [10] googlesheets4_1.0.1 cellranger_1.1.0 yaml_2.3.5
## [13] pillar_1.8.1 backports_1.4.1 glue_1.6.2
## [16] digest_0.6.29 rvest_1.0.3 colorspace_2.0-3
## [19] htmltools_0.5.3 pkgconfig_2.0.3 broom_1.0.1
## [22] haven_2.5.1 magick_2.7.3 scales_1.2.1
## [25] tzdb_0.3.0 googledrive_2.0.0 generics_0.1.3
## [28] farver_2.1.1 ellipsis_0.3.2 cachem_1.0.6
## [31] withr_2.5.0 cli_3.4.1 magrittr_2.0.3
## [34] crayon_1.5.1 readxl_1.4.1 evaluate_0.16
## [37] fs_1.5.2 fansi_1.0.3 xml2_1.3.3
## [40] textshaping_0.3.6 tools_4.2.1 hms_1.1.2
## [43] gargle_1.2.1 lifecycle_1.0.3 munsell_0.5.0
## [46] reprex_2.0.2 compiler_4.2.1 jquerylib_0.1.4
## [49] systemfonts_1.0.4 rlang_1.0.6 grid_4.2.1
## [52] rstudioapi_0.14 labeling_0.4.2 rmarkdown_2.16
## [55] gtable_0.3.1 DBI_1.1.3 curl_4.3.2
## [58] R6_2.5.1 lubridate_1.8.0 knitr_1.40
## [61] fastmap_1.1.0 bit_4.0.4 utf8_1.2.2
## [64] ragg_1.2.3 stringi_1.7.8 parallel_4.2.1
## [67] Rcpp_1.0.9 vctrs_0.4.2 dbplyr_2.2.1
## [70] tidyselect_1.1.2 xfun_0.32
测试数据
配套数据下载:US Honey Production
这篇关于20180521-A · US Honey Production · ggplot2 dplyr ggdraw geom_bar magick 柱状图 条形图 · R 语言数据可视化 案例 源码的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!