我想為一年中的國家/地區制作每日價值的影片 ggplot。
library(tidyverse)
library(ggplot2)
library(gganimate)
library(gifski)
library(png)
# Generate some fake data
n=365
df <- data.frame(country_name = rep(c("Country_1","Country_2","Country_3","Country_4","Country_5"), n, replace=FALSE),
date = rep(seq.Date(as.Date("2021-01-01"), as.Date("2021-12-31"), "day"),each=5), # each is number of countries
incidents=sample(1:100, size = 25, replace=TRUE
))
# Make cumulative number of events
df = df %>%
group_by(country_name) %>%
arrange(date) %>%
mutate(cumulative_incidents = cumsum(incidents)) %>%
ungroup()
# create integer rankings (I thought the *1 would make things smoother)
df = df %>%
group_by(date) %>%
mutate(rank = min_rank(-cumulative_incidents *1),
Value_rel = cumulative_incidents/cumulative_incidents[rank==1],
Value_lbl = paste0(" ",round(cumulative_incidents/1e9))) %>%
ungroup()
# make the static plot
my_plot = ggplot(df, aes(-rank,Value_rel, fill = country_name))
geom_col(width = 0.8, position="identity")
coord_flip()
geom_text(aes(-rank,y=0,label = country_name,hjust=0))
geom_text(aes(-rank,y=Value_rel,label = cumulative_incidents, hjust=0))
theme_minimal()
theme(legend.position = "none",axis.title = element_blank())
# animate along Year
transition_states(date,4,1)
# animate the plot
animate(my_plot, 100, fps = 25, duration = 20, width = 800, height = 600)
uj5u.com熱心網友回復:
您的資料的時間解析度非常高,您有 365 個時間點,但影片中只有 500 幀。因此,這些平滑切換發生在 500 / 365 = ~1.4 幀內并且不可見。
要么讓你的影片更長,降低資料的時間解析度,要么在過渡中手動編碼。例如,如果我們每月只提供一次資料,會發生以下情況:
df2 <- filter(df, date %in% seq(min(date), max(date), 'week'))
my_plot <- ggplot(df2, aes(-rank,Value_rel, fill = country_name))
geom_col(width = 0.8, position="identity")
coord_flip()
geom_text(aes(-rank,y=0,label = country_name,hjust=0))
geom_text(aes(-rank,y=Value_rel,label = cumulative_incidents, hjust=0))
theme_minimal()
theme(legend.position = "none",axis.title = element_blank())
# animate along Year
transition_states(date, transition_length = 10, state_length = 1)
animate(my_plot, fps = 25, duration = 20, width = 800, height = 600)

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/418219.html
標籤:
