# Is there anyway to use a for loop to define plot\_ly layout

**URL:** <https://community.plotly.com/t/is-there-anyway-to-use-a-for-loop-to-define-plot-ly-layout/29722>\
**Category:** Plotly R\
**Created:** [October 8, 2019, 2:40pm UTC](https://community.plotly.com/t/is-there-anyway-to-use-a-for-loop-to-define-plot-ly-layout/29722 "2019-10-08T14:40:54Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![mfethe1](https://avatars.discourse-cdn.com/v4/letter/m/838e76/32.png) [@mfethe1](https://community.plotly.com/u/mfethe1)\
**Post date:** [October 8, 2019, 2:40pm UTC](https://community.plotly.com/t/is-there-anyway-to-use-a-for-loop-to-define-plot-ly-layout/29722/1 "2019-10-08T14:40:54Z")

</div>

I want to use a for loop from a shinyapp to define multiple y axes in my plotly graph. Is this possible in r?

#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
