0

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.

Masoud
  • 535
  • 3
  • 19

1 Answers1

1

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

tamtam
  • 3,541
  • 1
  • 7
  • 21
  • Is there a way to assign different color to each categories. For example the color of first "a b c d" be red and other be blue? – Masoud May 31 '21 at 12:05
  • 1
    Different colors for tickfont are not implemented in plolty. There are workarounds with `ticktext` (https://stackoverflow.com/questions/58183962/how-to-color-ticktext-in-plotly), but I don't know if you can transfer this to multicategorial axis. – tamtam Jun 01 '21 at 15:17