✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
⚡️ Concerned about the grid? Kyle Baranko teaches how to predicting peak loads using XGBoost. Register for the August webinar!

Animating a scatter's trendline

Hello! I’m trying to animate the trendline of a scatterplot using plotly’s “frames.” The scatter markers animate successfully, and I’ve been able to overlay a static trendline that covers the un-frame’d data in the aggregate. I think the issue is coming from the fact that my “frames” variable is defined as ~DATE, and the regression function used to generate the trendline requires a formula, which takes the variables without the tilde. I’ve tried all sorts of variations, and nothing’s worked so far.

Here’s the code:

income_plot <- ts_cases %>%
plot_ly(
x = ~med_income,
y = ~pos_perhunK,
size = ~Pop,
color = ~borough,
frame = ~DATE,

hovertemplate = “”

type = 'scatter',
mode = 'markers'

) %>% layout(legend = list(orientation = ‘h’, yanchor = “center”, y = 100, xanchor = “center”, # use center of legend as anchor
x = 0.5), yaxis = list(
title = “”,
zeroline = FALSE,
showline = FALSE,
showticklabels = TRUE,
showgrid = TRUE
), xaxis = list(
title = “”,
zeroline = FALSE,
showline = FALSE,
showticklabels = TRUE,
showgrid = TRUE
)) %>%
add_trace(data=ts_cases, x=~med_income, y=~fitted(lm(pos_perhunK ~ med_income, data=ts_cases)), frame=~DATE, type=“scatter”, mode=“lines”, color=“black”)

income_plot

Thanks for your assistance!