R語言編程代寫動態圖可視化:如何、創建具有精美動畫的圖


 原文鏈接:http://tecdat.cn/?p=8003

 

 演示數據集

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.

靜態圖

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

 

基本

狀態之間的過渡長度將設置為與它們之間的實際時間差相對應。

標簽變量:frame_time。給出當前幀所對應的時間。

創建面:

讓視圖跟隨數據在每幀中

​ 

 

逐步衰減

 

​ 

 

顯示原始數據作為背景

您可以根據需要顯示過去和/或將來的原始數據並設置其樣式。

​ 

 

 

靜態圖

p <- ggplot(
  airquality,
  aes(Day, Temp, group = Month, color = factor(Month))
  ) +
  geom_line() +
  scale_color_viridis_d() +
  labs(x = "Day of Month", y = "Temperature") +
  theme(legend.position = "top")
p

​ 

 

讓數據逐漸出現

  • 按天顯示(x軸)

​ 

 

​ 

 

​ 

 

在數據的幾個不同階段之間進行轉換

數據准備:

library(dplyr)
mean.temp <- airquality %>%
  group_by(Month) %>%
  summarise(Temp = mean(Temp))
mean.temp
## # A tibble: 5 x 2
##   Month  Temp
##   <int> <dbl>
## 1     5  65.5
## 2     6  79.1
## 3     7  83.9
## 4     8  84.0
## 5     9  76.9

創建平均溫度的條形圖:

p <- ggplot(mean.temp, aes(Month, Temp, fill = Temp)) +
  geom_col() +
  scale_fill_distiller(palette = "Reds", direction = 1) +
  theme_minimal() +
  theme(
    panel.grid = element_blank(),
    panel.grid.major.y = element_line(color = "white"),
    panel.ontop = TRUE
  )
p

​ 

 

  • transition_states():

​ 

 

  • enter_grow()+ enter_fade()

保存動畫

如果需要保存動畫以備后用,可以使用該anim_save()功能。

 

 

如果您有任何疑問,請在下面發表評論。   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM