其他
R可视化:动态峰峦图
“医学和生信笔记,专注R语言在临床医学中的使用、R语言数据分析和可视化。主要分享R语言做医学统计学、临床研究设计、meta分析、网络药理学、临床预测模型、机器学习、生物信息学等。
💡专注R语言在🩺生物医学中的使用
本系列内容来自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
gganimate
让你的统计图动起来!动态交互图的绘制在 R 实际工作中应用的比较多,在 R 中我们可以使用 gganimate 包来快速完成一张动态图的绘制。
1. 一些环境设置
# 设置为国内镜像, 方便快速安装模块
options("repos" = c(CRAN = "https://mirrors.tuna.tsinghua.edu.cn/CRAN/"))
2. 设置工作路径
wkdir <- '/home/user/R_workdir/TidyTuesday/2018/2018-04-09_NFL_Positional_Salaries/src-b'
setwd(wkdir)
3. 加载 R 包
library(tidyverse)
library(lubridate)
library(gganimate)
library(ggridges)
library(ggtext)
library(ggimage)
library(patchwork)
library(magick)
library(gifski)
library(showtext)
# 在 Ubuntu 系统上测试的, 不加这个我画出来的汉字会乱码 ~
showtext_auto()
4. 加载数据
df_input <- readxl::read_excel("../data/nfl_salary.xlsx")
# 简要查看数据内容
glimpse(df_input)
## Rows: 800
## Columns: 11
## $ year <dbl> 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011, 20…
## $ Cornerback <dbl> 11265916, 11000000, 10000000, 10000000, 10000000, …
## $ `Defensive Lineman` <dbl> 17818000, 16200000, 12476000, 11904706, 11762782, …
## $ Linebacker <dbl> 16420000, 15623000, 11825000, 10083333, 10020000, …
## $ `Offensive LALBERT` <dbl> 15960000, 12800000, 11767500, 10358200, 10000000, …
## $ Quarterback <dbl> 17228125, 16000000, 14400000, 14100000, 13510000, …
## $ `Running Back` <dbl> 12955000, 10873833, 9479000, 7700000, 7500000, 703…
## $ Safety <dbl> 8871428, 8787500, 8282500, 8000000, 7804333, 76527…
## $ `Special Teamer` <dbl> 4300000, 3725000, 3556176, 3500000, 3250000, 32250…
## $ `Tight End` <dbl> 8734375, 8591000, 8290000, 7723333, 6974666, 61333…
## $ `Wide Receiver` <dbl> 16250000, 14175000, 11424000, 11415000, 10800000, …
# 检查数据的列名
colnames(df_input)
## [1] "year" "Cornerback" "Defensive Lineman"
## [4] "LneALBERTr" "Offensive Lineman" "Quarterback"
## [7] "Running Back" "Safety" "Special Teamer"
## [10] "Tight End" "Wide Receiver"
5. 数据预处理
# 整理数据, 从宽数据透视到长数据转换
df_tidy <- df_input %>% gather(key = position, value = salary, -year)
# 创建 进攻 Offense 和 防守 Defense 类别
# 建议使用 dplyr::mutate 形式调用函数, 不然容易与 plyr 中的函数冲突 (因为我自己就报错了...)
df_tidy <- df_tidy %>% mutate(salary = salary / 10**6,
year = year(as.Date.character(year, format = "%Y")),
status = case_when(
position %in%
c("Cornerback", "Defensive Lineman", "Linebacker", "Safety", "Special Teamer") ~ "Defense",
position %in% c("Quarterback", "Offensive Lineman", "Running Back", "Tight End", "Wide Receiver") ~ "Offense")) %>%
group_by(position, year) %>%
top_n(50, salary)
# 删除缺失值的观测
df_plot <- na.omit(df_tidy)
glimpse(df_plot)
## Rows: 4,010
## Columns: 4
## Groups: position, year [80]
## $ year <dbl> 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2011, 2…
## $ position <chr> "Cornerback", "Cornerback", "Cornerback", "Cornerback", "Corn…
## $ salary <dbl> 11.265916, 11.000000, 10.000000, 10.000000, 10.000000, 9.2441…
## $ status <chr> "Defense", "Defense", "Defense", "Defense", "Defense", "alertb…
6. 绘制第一张动图 (Defense)
# PS: 方便讲解, 我这里进行了拆解, 具体使用时可以组合在一起
gg <- ggplot(data = df_plot %>% filter(status == "Defense"),
aes(x = salary, y = fct_reorder(position, salary, median), fill = position))
# geom_density_ridges() 绘制峰峦图
# scale值小于1可以防止重叠
gg <- gg + geom_density_ridges(scale = .95,
size = .25,
na.rm = TRUE,
alpha = .75,
rel_min_height = 0.05,
quantile_lines = TRUE,
show.legend = FALSE)
gg <- gg + scale_x_continuous(breaks = seq(0, 20, 5), limits = c(0, 20), labels = function(l) {paste0("$",round(l,1), "M")})
gg <- gg + scale_y_discrete(limits = rev)
# transition_states() 按照给定的列分成不同时态的数据动态显示
gg <- gg + transition_states(year, transition_length = 3, state_length = 1)
# ease_aes() 控制 gganimate 中美学或变量的动作, quadratic-in-out 二次进与出
gg <- gg + ease_aes('quadratic-in-out')
# enter_fade() 淡入
gg <- gg + enter_fade()
# exit_fade() 淡出
gg <- gg + exit_fade()
gg <- gg + ggthemes::theme_fivethirtyeight()
gg <- gg + labs(title = "<br>",
subtitle = "<br>防守 Defense",
x = NULL,
y = NULL,
caption = '<br>')
# theme_minimal() 去坐标轴边框的最小化主题
gg <- gg + theme_minimal()
# theme() 实现对非数据元素的调整, 对结果进行进一步渲染, 使之更加美观
gg <- gg + theme(
# legend.position 设置图例位置, "none" 表示不显示图例
legend.position = "none",
# plot.title.position 设置主标题位置
plot.title.position = 'plot',
# plot.title 主标题
plot.title = element_markdown(face = "bold", size = 18, hjust = 1),
# plot.subtitle 次要标题
plot.subtitle = element_markdown(face = "italic", size = 10, colour = "azure4", hjust = .5),
# plot.caption 说明文字
plot.caption = element_markdown(colour = "dodgerblue4", size = 10, hjust = 1),
# axis.text.x X-坐标轴文本
axis.text.x = element_text(size = 10),
# axis.text.y Y-坐标轴文本
axis.text.y = element_text(size = 10))
gg.gif <- animate(gg, renderer=gifski_renderer(), width = 395.136, height = 444.528, duration = length(unique(df_plot$year)))
7. 绘制第二张动图 (Offense)
# PS: 方便讲解, 我这里进行了拆解, 具体使用时可以组合在一起
hh <- ggplot(data = df_plot %>% filter(status == "Offense"),
aes(x = salary, y = fct_reorder(position, salary, median), fill = position))
# geom_density_ridges() 绘制峰峦图
# scale值小于1可以防止重叠
hh <- hh + geom_density_ridges(scale = .95,
size = .25,
na.rm = TRUE,
alpha = .75,
rel_min_height = 0.05,
quantile_lines = TRUE,
show.legend = FALSE)
hh <- hh + scale_x_continuous(breaks = seq(0, 20, 5), limits = c(0, 20), labels = function(l) {paste0("$",round(l,1), "M")})
hh <- hh + scale_y_discrete(limits = rev, position ='right')
# transition_states() 按照给定的列分成不同时态的数据动态显示
hh <- hh + transition_states(year, transition_length = 3, state_length = 1)
# ease_aes() 控制 gganimate 中美学或变量的动作, quadratic-in-out 二次进与出
hh <- hh + ease_aes('quadratic-in-out')
# enter_fade() 淡入
hh <- hh + enter_fade()
# exit_fade() 淡出
hh <- hh + exit_fade()
hh <- hh + geom_image(aes(x = 17.5, y = 5.3, image = "../data/icon.png"), size = 0.08)
hh <- hh + ggthemes::theme_fivethirtyeight()
hh <- hh + labs(title = "<br>{closest_state}年·橄榄球队球员的薪酬水平",
subtitle = "<br>防守 Defense",
x = NULL,
y = NULL,
caption = "<br><span>NFL·Quarterback·Salaries<br><br>graph·by·萤火之森</span>")
# theme_minimal() 去坐标轴边框的最小化主题
hh <- hh + theme_minimal()
# theme() 实现对非数据元素的调整, 对结果进行进一步渲染, 使之更加美观
hh <- hh + theme(
# legend.position 设置图例位置, "none" 表示不显示图例
legend.position = "none",
# plot.title 主标题
plot.title = element_markdown(face = "bold", size = 18, hjust = 1),
# plot.subtitle 次要标题
plot.subtitle = element_markdown(face = "italic", size = 10, colour = "azure4", hjust = .5),
# plot.caption 说明文字
plot.caption = element_markdown(colour = "dodgerblue4", size = 10, hjust = 1),
# axis.text.x X-坐标轴文本
axis.text.x = element_text(size = 10),
# axis.text.y Y-坐标轴文本
axis.text.y = element_text(size = 10))
hh.gif <- animate(hh, renderer=gifski_renderer(), width = 395.136, height = 444.528, duration = length(unique(df_plot$year)))
8 合并动图
gg.mgif <- image_read(gg.gif)
hh.mgif <- image_read(hh.gif)
new.gif <- image_append(c(gg.mgif[1], hh.mgif[1]))
for(i in 2:69){
merge.gif <- image_append(c(gg.mgif[i], hh.mgif[i]))
new.gif <- c(new.gif, merge.gif)
}
new.gif
测试数据
配套数据下载:nfl_salary.xlsx[2]
本次内容来自CSDN,我只是搬运工,项目地址:数绘小站的博客_CSDN博客-Tidy Tuesday[3]
参考资料
[1]CSDN项目地址: https://blog.csdn.net/Albert_XN?type=blog
[2]数据下载: https://gitee.com/tidytuesday/tt-data/tree/master/2018/2018-04-09
[3]CSDN项目地址: https://blog.csdn.net/Albert_XN?type=blog
咨询交流等,欢迎加入🐧QQ交流群:613637742
往期推荐