I have written below snippet of code to plot dual-axis charts using plotly in R.
Code:
## Date creation dtMasterWithtotals <- data.table("Period_Month" = c('7/1/2017', '9/1/2017'), A = c(171, 448), B = c(0, 655), C = c(476, 812)) ## Vectors to select categories for primary and secondary axis vecPrimaryAxis <- c("A", "B") vecSecondaryAxis <- c("C") ## X-axis properties ax <- list( type = "category", categoryorder = "array", categoryarray = dtMasterWithtotals[order(as.Date(dtMasterWithtotals[, Period_Month])),], showgrid = TRUE, showline = TRUE, autorange = TRUE, showticklabels = TRUE, ticks = "outside", tickangle = 0 ) ## arrange columns in an order – TBD ## The plot function below assumes that the data will be in format, Period_Month, A, B,C. ## Plot function plot <- plot_ly(dtMasterWithtotals, x = ~Period_Month, y = dtMasterWithtotals[[2]], type = "scatter", mode = 'lines', name = names(dtMasterWithtotals)[2]) if(length(vecPrimaryAxis) > 1){ t <- (3 + length(vecPrimaryAxis) - 2) for (i in 3:t){ plot <- add_trace(plot, x = ~Period_Month, y = dtMasterWithtotals[[i]], type = "scatter", mode = "lines", name = names(dtMasterWithtotals)[i]) %>% layout(xaxis = ax) } } if(length(vecSecondaryAxis) > 0){ p <- 2 + length(vecPrimaryAxis) q <- p + length(vecSecondaryAxis) - 1 for (j in (p:q)){ plot <- add_trace(plot, x = ~Period_Month, y = dtMasterWithtotals[[j]], type = "scatter", mode = "lines", yaxis = "y2", name = names(dtMasterWithtotals)[j]) %>% layout(yaxis2 = list(overlaying = "y", side = "right"), xaxis = ax) } } When trying to plot A and B on primary y-axis and C on secondary y-axis, the last trace (in this case C) overlaps the second trace (in this case B), resulting in two traces instead of three. However, on hover the new trace shows the correct value labels, but comes up incorrectly (at the wrong position) in the visualization.
Let me know if you require any other detail.
Thanks.
