0

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.

0

1 Answer 1

1

If I understand correctly what you want, in fact, there is no problem with your code. You just need to set manually your y and y2 axis. To make it easier to visualize I simply reversed the y2 axis. If you try this:

plot_ly() %>% add_lines(data=dtMasterWithtotals, x = ~Period_Month, y = ~A, name = "A") %>% add_lines(data=dtMasterWithtotals, x = ~Period_Month, y = ~B, name = "B") %>% add_lines(data=dtMasterWithtotals, x = ~Period_Month, y = ~C, name = "C", yaxis = "y2") %>% layout(xaxis = ax, yaxis2 = list(overlaying = "y", side = "right", autorange="reversed")) 

It will give you this:

enter image description here

As you can see, all three lines are visible and all three displayed the right values.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.