Search code examples
rr-plotly

Draw scatter plot with two nominal variables with Plotly package in R


The question is how to draw following plot using Plotly package in R?

enter image description here

I have a dataframe with 166 columns. I should use a loop for plot all the columns. I try as follows:

  X1<-rep(c("A","B"),each=4)
  X2<-rep(letters[1:4],len=length(X1))
  Y1<-c(1, 1.5, 1.3, 1.4, 1.8, 1.7, 1.5, 1.6)
  Y2<-Y1^2;Y3<-log(Y1)
  data_f<-data.frame(X1=X1,X2=X2,Y1=Y1,Y2=Y2,Y3=round(Y3,2))
  plt <- plot_ly()%>%
  layout(title = "",
     xaxis = list(title = ""),
     yaxis = list (title = "") )


 for( i in 3:dim(data_f)[2]){
 text1<-paste0('X1 : ', data_f$X1, '\n',
            'X2 : ', data_f$X2, '\n',
            'Y1 : ', data_f$Y1, '\n',
            'Y2 : ', data_f$Y2, '\n',
            'Y3 : ', data_f$Y3 
 )

plt<-plt %>% add_trace(x=paste(data_f$X1,data_f$X2)
                               ,y=data_f[,i],
                               type='scatter',
                               mode='line+markers',
                               line=list( width = 4),
                               marker=list(size=15),
                               text =text1,
                               hoverinfo = 'text'
                               
    )  
  }
  plt

and the outcome is as follows:

enter image description here

Thanks in advance for any help you are able to provide.


Solution

  • Code

    plt <- plot_ly(data = data_f,
                   x=~ list(X1, X2))%>%
      layout(title = "Chart Title",
             xaxis = list(title = ""),
             yaxis = list (title = ""),
             hovermode="x unified")
    
    for(i in 3:5){
      plt <- plt %>%
        add_trace(y= data_f[,i],
                  mode='lines+markers',
                  type = "scatter",
                  name = colnames(data_f)[i])
    }
    
    
    plt
    

    Multicategorical axis (x-axis with two levels) can be set with x =~ list(X1, X2). And a combinded hovertemplate can the achieved through hovermode="x unified".

    Plot
    enter image description here