1

I'm trying to create a scatter plot where the user can dynamically change the X and Y axis. I have it mostly completed, but I'm running into this weird hiccup.

The first time I change the X dropdown, the scatter plot will be incorrect. However, once I change the Y dropdown the scatter plot corrects itself, but it loses it's color-groupings. Example code:

# Get libraries
library(plotly)

set.seed(123)
index <- 1:24
x1 <- rnorm(24, 4, 3)
x2 <- rnorm(24, 3, 4)
y1 <- rnorm(24, 5, 2)
y2 <- rnorm(24, 2, 5)
type <- rep(c("A", "B", "C"), 8)

df <- data.frame(x1, x2, y1, y2, type)

p <- plot_ly(df, x = ~x1, y = ~y1, color = ~type, type = "scatter", mode = "markers",  
  text = ~paste("Index: ", index)) %>% 
  layout(
    updatemenus = list(
      ## X Axis ##
      list(
        y = 0.6,
        buttons = list(
          list(method = "restyle",
               args = list("x", list(df$x1)),  # put it in a list
               label = "x1"),
          list(method = "restyle",
               args = list("x", list(df$x2)),  # put it in a list
               label = "x2"))),
      ## Y Axis ##
      list(
        y = 0.5,
        buttons = list(
          list(method = "restyle",
               args = list("y", list(df$y1)),  # put it in a list
               label = "y1"),
               list(method = "restyle",
                    args = list("y", list(df$y2)),  # put it in a list
                    label = "y2")))
    ))

p

After it pops up in your viewer, click the "X1" dropdown and select "X1" again: notice how the graph updates incorrectly. Next, click the "Y1" dropdown and select "Y1": notice how the graph looks the same as the original, but the color-groupings no longer exist and I believe the indexes got mixed up.

Is there an easy fix to what I'm doing wrong?

CoolGuyHasChillDay
  • 659
  • 1
  • 6
  • 21
  • Tagging @aocall since you helped me with my boxplot question, thanks! – CoolGuyHasChillDay Jan 03 '18 at 05:47
  • I tried this before, but was not able to accomplish it. I had to write my own plotly Javascript htmlwidget in order to do things like this. Sorry! See [here](https://stackoverflow.com/questions/40719220/dropdown-menu-to-select-x-y-and-color-plotly). – alan ocallaghan Jan 03 '18 at 12:04

0 Answers0