How to subplot already created polar graphs with plotly?

Viewed 61

I want to draw 2 subplots for polar graphs with plotly. The standard way is to write :

p<-plot_ly(type="barpolar",r=1,theta=2)%>%add_trace(r=1,theta=20,subplot="polar2")

Yet, if my graphs are already created :

p<-plot_ly(type="barpolar",r=1,theta=2)
p2<-plot_ly(type="barpolar",r=1,theta=20)

How can I do, as subplot function is not an option ?

1 Answers

Since I did not find a way, I wrote my own function (not sure this works for every cases)

subplot_polar<-function(...,nrows=1)
{
  require(purrr);require(magrittr)
 l<-list(...)
 ll<-length(l)
 p<-l[[1]]
 p<-reduce(c(list(p),2:ll),function(p,i)
 {   
  if (length(l[[i]]$x$attrs)==1) return(p)
   tempname<-tempfile(pattern="",tmpdir="")%>%gsub("/","",.)
   p$x$attrs[[tempname]]<-l[[i]]$x$attrs[[2]]
   p$x$attrs[[tempname]]$subplot<-p0("polar",i)
   return(p)
 })
 ncols<-ceiling(ll/nrows)
 
  p<-reduce(c(list(p),1:ll),function(p,i)
  {
     arg<-list(
       domain = list(
         x=c((i-1)%%ncols,(i-1)%%ncols+1)/ncols,
         y=c(floor((i-1)/ncols),floor((i-1)/ncols)+1)/nrows
       ))
     l<-list(p,arg)
     names(l)<-c("p",p0("polar",if (i>1) i else ""))
     p<-do.call(plotly::layout,l)
   })
 return(p)
}

Example :

p1<-plot_ly(type="barpolar")%>%add_trace(r=1,theta=2)
p2<-plot_ly(type="barpolar")%>%add_trace(r=1,theta=20)
p3<-plot_ly(type="barpolar")%>%add_trace(r=1,theta=40)

subplot_polar(p1,p2,p3,p2,p3,p1,p3,p2,nrows=3)

Related