I'm trying to graph spend and profitability data for a set of ads on a daily basis over time. For a given date range, I loop through the range and create a date frame. Each of these tables are appended to a list as separate data frames.
Here is some sample code:
l <- list()
df1 <- tribble(
~Ad, ~Spend, ~Profitability,
"Cat", 10000, 0.21,
"Movie", 20000, -0.05,
"Dog", 8000, 0.07)
l[1] <- list(df1)
df2 <- tribble(
~Ad, ~Spend, ~Profitability,
"Cat", 14000, 0.25,
"Movie", 21000, -0.08,
"Dog", 8000, 0.09,
"TV", 4000, .31)
l[2] <- list(df2)
df3 <- tribble(
~Ad, ~Spend, ~Profitability,
"Cat", 13000, 0.18,
"Movie", 23000, -0.11,
"TV", 7000, .25)
l[3] <- list(df3)
So far, I've been graphing each of the tables as scatter plots (profitability as the y axis, spend as the x axis) and saving them as separate pngs to make them into a gif, but it looks very choppy.
This is an example of one of the scatter graphs:
ggplot(as.data.frame(l[1]), aes(x = Spend, y = Profitability, color = Ad)) + geom_point(size = 3) + xlim(0, 30000) +
scale_y_continuous(labels = scales::percent, limits = c(-0.25, 0.5)) + geom_text(aes(label = Ad), size = 2, vjust = -2)
My question is, how could I animate this gif so that the points move continuous from day to day (i.e. the 'Cat' scatter point will move from (10000,0.21) to (14,000, 0.25) to (13,000, 0.18)?
One other complication is that the set of ads isn't necessarily the same from day to day (table to table) since some ads don't spend at all on certain days. If an ad isn't there on a certain, I the corresponding scatter point to travel to (0,0).
Thank you!
library(purrr); library(gganimate)
l %>%
map_df(magrittr::extract, .id = "table",
c("Ad", "Spend", "Profitability")) %>%
complete(table, Ad, fill = list(Spend = 0, Profitability = 0)) %>%
ggplot(aes(Spend, Profitability, color = Ad)) +
geom_point() +
transition_states(table)