Search code examples
rgraph3dplotly

Plotly in R: 3D Line Graphs - Preventing One Continuous Line


I'm new to using Plotly in R.

I am trying to construct a 3d line graph.

I am trying to achieve a graph that looks like this:

enter image description here

The above is my objective and I can't seem to make it work.

When I impliment what I think the right code is, I get one continuous line (so the last value of the first series line above is connected to the first value of the second series, etc).

Here is my result (you are viewing from an angle that shows the problem of the "looping"):

enter image description here

My code is here:

fig <- plot_ly(df_cohort_master, y = ~ord_month, x = ~cohort, z = ~conversions, 
                  type = 'scatter3d', mode = 'lines',color=~conversions) %>%
                  layout(
                    scene= list(
                      xaxis = list(autorange = "reversed"),
                      yaxis = list(autorange = "reversed")))

suppressWarnings(print(fig))

And here is what my data looks like:

enter image description here

What am I doing wrong?

Thanks in advance.


Solution

  • Perhaps you could try using split to separate into multiple traces based on your cohort.

    Here's an example with made up data based on your post.

    library(plotly)
    
    set.seed(123)
    
    df_cohort_master <- data.frame(
      cohort = rep(1:4, times = 5),
      ord_month = rep(1:4, each = 5),
      conversions = sample(20, 20)
    )
    
    plot_ly(df_cohort_master,
            x = ~cohort, 
            y = ~ord_month, 
            z = ~conversions, 
            type = 'scatter3d', 
            mode = 'lines',
            split = ~cohort) %>%
      layout(
        title = "3D Scatter plot", 
        scene = list(
          camera = list(
            eye = list(x = 1, y = 2, z = 2)
          )
        )
      )
    

    Plot

    3d plot with multiple traces