简体   繁体   中英

Is there a plotly function that switches the legend and color of a plot based on different conditions in the data frame?

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
???

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
  )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM