是否存在可根据数据帧中的不同条件切换图例的图例和颜色的plotly函数?

时间:2019-01-22 19:55:44

标签: r ggplotly

除了aes()中引用的颜色外,我有两个相同的图。我想使用plotly在两个图的配色方案之间切换。我该怎么办?

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

1 个答案:

答案 0 :(得分:1)

我建议您阅读按钮的文档 https://plot.ly/r/custom-buttons/

这是我解决这个问题的尝试。

 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
  )