Make a plot_ly plot, combining two sine waves with nearby frequencies through multiplcation. Give controls over the phase of the second sine wave. See what it does to the result.
Trig identity:
cos(α + β) = cos(α) cos(β) – sin(α) sin(β)
Rearranged:
sin(α) sin(β) = cos(α) cos(β) + cos(α + β)
So if one wave has frequency of 1 Hz, and other 2 Hz, what does phase do to signal?
Actually Plot_ly plots have all data evaluated ahead of time, with the controls only determining what data gets called upon.
For a good example, look here: https://plotly.com/r/sliders/
library(plotly)
## Loading required package: ggplot2
##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
x <- seq(0,10, length.out = 2000)
y1 <- sin(2*pi*1*x)
#freqs <- seq(from=0.25, to = 5, by = 0.5)
phase <- seq(from = 0, to = 2*pi, by = 2*pi/16)
# create data
aval <- list()
p_ind <- 0
for(p in phase){
p_ind <- p_ind + 1
y2=sin(2*pi*2*x + p)
aval[[p_ind]] <-list(visible = FALSE,
name = paste0('p = ', p),
x=x,
y=y1*y2)
}
aval[3][[1]]$visible = TRUE #make the 3rd phase visible, the default slider step
See how all the lines are added through add_lines inside the for loop.
# create steps and plot all traces
steps <- list()
fig <- plot_ly()
for (i in 1:length(aval)) {
fig <- add_lines(fig,x=aval[i][[1]]$x, y=aval[i][[1]]$y, visible = aval[i][[1]]$visible,
name = aval[i][[1]]$name, type = 'scatter', mode = 'lines', hoverinfo = 'name',
line=list(color='00CED1'), showlegend = FALSE)
step <- list(args = list('visible', rep(FALSE, length(aval))),
method = 'restyle',
label = phase[i])
step$args[[2]][i] = TRUE
steps[[i]] = step
}
fig <- fig %>%
layout(title = "y = sin(1 Hz)*sin(2 Hz + phase)",
sliders = list(list(active = 3,
currentvalue = list(prefix = "Phase: "),
steps = steps)))
fig #show the plot