0

I have two plots that are identical except for the colour referenced in aes(). I would like to use plotly to toggle between the two plots' color schemes. How might I do this?

require(ggplot2)
require(plotly)

#DF Construction
col1 <- c(84, 55, 69, 65, 80, 67, 90, 75, 89, 88)
col2 <- c(81, 70, 88, 78, 77, 72, 88, 79, 88, 90)
col3 <- c("L2", "L1", "L2", "L1", "L1", "L2", "L1", "L2", "L2", "L2")
col4 <- c("Ready", "Not", "Not", "Not", "Not", "Not", "Ready", "Not", "Ready", "Ready")
df <- data.frame(col1, col2, col3, col4)

#ggplot Construction
plot1 <- ggplot(df, aes(x = col1, y = col2, colour = col3)) +
             geom_jitter()
plot2 <- ggplot(df, aes(x = col1, y = col2, colour = col4)) +
             geom_jitter()

#Plotly Toggle
???
Z.Lin
  • 28,055
  • 6
  • 54
  • 94

1 Answers1

2

I suggest you read the documentation for the buttons https://plot.ly/r/custom-buttons/

Here's my attempt at solving this problem.

 button_list = list(
  list(
    type = "buttons",
    buttons = list(
      list(method = "update",
           label = "col3",
           args = list(
             list(visible = c(TRUE, TRUE, FALSE, FALSE)))),
      list(method = "update",
           label = "col4",
           args = list(
             list(visible = c(FALSE, FALSE, TRUE, TRUE))))
    )
  )
)

plot_ly(df, x = ~col1, y = ~col2) %>%
  add_markers(color = ~col3, colors = c("red","blue", "red", "blue")) %>%
  add_markers(color = ~col4, colors = c("red", "blue", "red", "blue")) %>%
  layout(
    updatemenus = button_list
  )
moho wu
  • 471
  • 4
  • 13
  • Thank you very much for the help. It is so close! The main issue is that in my posted code, I have two ggplots with the appropriate designs. How can I use those ggplots (I'm using ggplotly to convert them) with the button method. At the moment, the "colour" parameter in the ggplot and the "color" paramter in add_markers are not matching up. Sorry if I'm missing something easy. – Banjerin' Foo' Jan 23 '19 at 19:03
  • 1
    I think you can't simply just use `ggplotly` to convert your `ggplot` to `plotly` in case since there's no equivalent button feature in `ggplot`. You'll have to write you graph in native `plotly` code. – moho wu Jan 23 '19 at 21:06
  • That would make sense from what I'm seeing. Thank you! – Banjerin' Foo' Jan 23 '19 at 21:44