Chapter 10 Animations
10.1 Intro to animations
10.1.1 Basic Example
library(plotly)
<- data.frame(
df x = c(1,2,1),
y = c(1,2,1),
f = c(1,2,3)
)
<- df %>%
fig plot_ly(
x = ~x,
y = ~y,
frame = ~f,
type = 'scatter',
mode = 'markers',
showlegend = F
)
fig
10.1.2 Mulitple Trace Animations
library(plotly)
library(gapminder)
<- gapminder
df <- df %>%
fig plot_ly(
x = ~gdpPercap,
y = ~lifeExp,
size = ~pop,
color = ~continent,
frame = ~year,
text = ~country,
hoverinfo = "text",
type = 'scatter',
mode = 'markers'
)<- fig %>% layout(
fig xaxis = list(
type = "log"
)
)
fig
10.2 Cumulative animations
10.2.1 Cumulative Lines Animation
library(plotly)
<- function(dat, var) {
accumulate_by <- lazyeval::f_eval(var, dat)
var <- plotly:::getLevels(var)
lvls <- lapply(seq_along(lvls), function(x) {
dats cbind(dat[var %in% lvls[seq(1, x)], ], frame = lvls[[x]])
})::bind_rows(dats)
dplyr
}
<- txhousing
df <- df %>%
fig filter(year > 2005, city %in% c("Abilene", "Bay Area"))
<- fig %>% accumulate_by(~date)
fig
<- fig %>%
fig plot_ly(
x = ~date,
y = ~median,
split = ~city,
frame = ~frame,
type = 'scatter',
mode = 'lines',
line = list(simplyfy = F)
)<- fig %>% layout(
fig xaxis = list(
title = "Date",
zeroline = F
),yaxis = list(
title = "Median",
zeroline = F
)
) <- fig %>% animation_opts(
fig frame = 100,
transition = 0,
redraw = FALSE
)<- fig %>% animation_slider(
fig hide = T
)<- fig %>% animation_button(
fig x = 1, xanchor = "right", y = 0, yanchor = "bottom"
)
fig
10.2.2 Filled-Area Animation
library(plotly)
library(quantmod)
getSymbols("AAPL",src='yahoo')
<- data.frame(Date=index(AAPL),coredata(AAPL))
df <- tail(df, 30)
df $ID <- seq.int(nrow(df))
df
<- function(dat, var) {
accumulate_by <- lazyeval::f_eval(var, dat)
var <- plotly:::getLevels(var)
lvls <- lapply(seq_along(lvls), function(x) {
dats cbind(dat[var %in% lvls[seq(1, x)], ], frame = lvls[[x]])
})::bind_rows(dats)
dplyr
}
<- df %>% accumulate_by(~ID)
df <- df %>% plot_ly(
fig x = ~ID,
y = ~AAPL.Close,
frame = ~frame,
type = 'scatter',
mode = 'lines',
fill = 'tozeroy',
fillcolor='rgba(114, 186, 59, 0.5)',
line = list(color = 'rgb(114, 186, 59)'),
text = ~paste("Day: ", ID, "<br>Close: $", AAPL.Close),
hoverinfo = 'text'
)<- fig %>% layout(
fig title = "AAPL: Last 30 days",
yaxis = list(
title = "Close",
range = c(0,250),
zeroline = F,
tickprefix = "$"
),xaxis = list(
title = "Day",
range = c(0,30),
zeroline = F,
showgrid = F
)
) <- fig %>% animation_opts(
fig frame = 100,
transition = 0,
redraw = FALSE
)<- fig %>% animation_slider(
fig currentvalue = list(
prefix = "Day "
)
)
fig
## [1] "AAPL"