更多關於R語言,ggplot2繪圖,生信分析的內容,敬請關注小號。
介紹一個主要用於繪制動畫的ggplot2的擴展包---gganimate包。
Hans Rosling的關於“New Insights on Poverty”的TED演講
下面嘗試使用 gganimate 包和 gapminder 數據集,實現類似可視化過程。
一 加載R包,數據
#R包安裝
install.packages("devtools")
library(devtools)
install_github("thomasp85/gganimate")
install.packages("gapminder")
#加載
library(gganimate)
library(gapminder)
#查看數據
head(gapminder)
# A tibble: 6 x 6
country continent year lifeExp pop gdpPercap
<fct> <fct> <int> <dbl> <int> <dbl>
1 Afghanistan Asia 1952 28.8 8425333 779.
2 Afghanistan Asia 1957 30.3 9240934 821.
3 Afghanistan Asia 1962 32.0 10267083 853.
4 Afghanistan Asia 1967 34.0 11537966 836.
5 Afghanistan Asia 1972 36.1 13079460 740.
6 Afghanistan Asia 1977 38.4 14880372 786.
數據集包括全球主要國家在1952-2007年的人均GDP增長、預期壽命以及人口增長的數據 。
二 ggplot2繪制
使用ggplot2繪制
theme_set(theme_bw())
p <- ggplot(gapminder,
aes(x = gdpPercap, y=lifeExp, size = pop, colour = country)) +
geom_point(show.legend = FALSE, alpha = 0.7) +
scale_color_viridis_d() +
scale_size(range = c(2, 12)) +
scale_x_log10() +
labs(x = "GDP per capita", y = "Life expectancy")
p
三 gganimate 動態
1. transition_time()
核心函數,添加動態
p + transition_time(year) + labs(title = "Year: {frame_time}")
2 按需設置
1)添加小尾巴
p + transition_time(year) +
labs(title = "Year: {frame_time}") +
shadow_wake(wake_length = 0.1, alpha = FALSE)
2)原數據做背景
p + transition_time(year) +
labs(title = "Year: {frame_time}") +
shadow_mark(alpha = 0.3, size = 0.5)
參考資料
https://www.datanovia.com/en/blog/gganimate-how-to-create-plots-with-beautiful-animation-in-r/
TED:https://www.ted.com/talks/hans_rosling_the_best_stats_you_ve_ever_seen?language=zh-TW
◆ ◆ ◆ ◆ ◆
精心整理(含圖版)|你要的全拿走!有備無患 (R統計,ggplot2繪圖,生信圖形可視化匯總)
【覺得不錯,右下角點個“在看”,期待您的轉發,謝謝!】