I'm trying to animate a map graph using gganimate
but am running into the following error:
Error in seq.default(range[1], range[2], length.out = nframes) :
'from' must be a finite number
It seems like this usually occurs when the variable used for transition_time()
isn't numeric or the data's in the wrong form, but I don't know how that could be in my case; my data's in the proper long format and the variable for transition_time()
is numeric and always finite.
Is this a specific issue with plot_usmap()
? Am I missing something obvious?
My data is on GitHub. Code below:
library("usmap")
library("ggplot2")
library("gganimate")
load("helpdata.Rda")
check = plot_usmap(data = df_map, values = "frac_cov") +
scale_fill_stepsn(breaks=c(-100, 0, 0.1, 0.2, 0.3, 0.4, 0.5,
0.6, 0.7, 0.8, 0.9, 1, 100),
colors=c("red", "gray100", "gray90", "gray80", "gray70", "gray60",
"gray50", "gray40", "gray30", "gray20", "gray10", "red"),
na.value="white") +
labs(fill = "", title = "Fraction of excess deaths\nattributed to COVID-19") +
theme(legend.position = "right", plot.title = element_text(hjust = 0.5)) +
transition_time(month)
anim <- animate(check, nframes=9, fps=1)
Thanks so much!
Your dataset has 50 unique fips values. The map data in the usmap
package comes with 51. When plot_usmap
creates the ggplot layers, it merged your dataset with the map data by fips code, which adds on NA values to the month column since one of the fips codes has no match.
(transition_time
makes a fuss about this while transition_state
doesn't. I'm not familiar enough with the gganimate package to theorize why that's the case.)
Add the following to your dataset before plotting. It should solve the problem:
df_map <- rbind(df_map,
data.frame(month = sort(unique(df_map$month)),
frac_cov = 0,
fips = 11)) # the missing fips value
Result after running the same animation code shown in the question: