I'm trying to use a for loop to define multiple y axes in plotly graph in R. Below is an example. Does anyone have any suggestions or experience with getting something like this to work?
#example of dataset of plotly to plot multiple y axes in for loop
library(plotly)
len = length(names(mtcars))
names = names(mtcars)
n=0
p= plot_ly()
for (i in names){
n=n+1
p=add_trace(p,data = mtcars, x = mtcars[,"mpg"], y = mtcars[,i], yaxis = paste0('y',ifelse(n==1,'',n)), type = 'scatter', mode = 'scatter')
}
n=0
for (i in 1:len)
{n=n+1
layout(p,assign(paste0('yaxis', ifelse(n==1,"",n)),list( overlaying = "y", side = ifelse((n %% 2) == 0,'right','left'), title = paste0(n, " y axis")
)) )
}
p
I'm thinking that the assign with the multiple paste0's may be causing alot of problems with this. Is there any other way you all can think of to accomplish this? I'm trying to incorporate this into a shiny app to plot functions based on user input. So an lapply() or for loop is ideal. I'm not sure if I'll be able to predefine the yaxes so that all selected variables are plotted. Any help is greatly appreciated. Is there any instance of setting yaxes like this in R? It must be possible right?