How to link plotly traces for legend and colour selection?

非 Y 不嫁゛ 提交于 2019-12-04 09:57:04

Revisiting history for posterity

Several changes to ggplot2 and plotly in the intervening time since this question was first asked. In the current version (4.7.1) there is an argument legendgroup that attends to solving the problem.

Lazy code

Please forgive the minimum effort placed on elegant coding, however, this extension to the MWE demonstrates the ability to show/hide traces by group.

df1_G1 <- df1 %>% filter(group == "G1")
df2_G1 <- df2 %>% filter(group == "G1")
df1_G2 <- df1 %>% filter(group == "G2")
df2_G2 <- df2 %>% filter(group == "G2")
df1_G3 <- df1 %>% filter(group == "G3")
df2_G3 <- df2 %>% filter(group == "G3")
df1_G4 <- df1 %>% filter(group == "G4")
df2_G4 <- df2 %>% filter(group == "G4")

plot_ly(type = "scatter", mode = "markers") %>%
  add_trace(df1_G1, x = df1_G1$x, y = df1_G1$y, color = I("red"),
            legendgroup = "G1", name = "G1 - scatter") %>%
  add_trace(df2_G1, x = df2_G1$x, y = df2_G1$y, color = I("red"),
            legendgroup = "G1", name = "G1 - line", mode = "lines") %>%
  add_trace(df1_G2, x = df1_G2$x, y = df1_G2$y, color = I("green"), 
            legendgroup = "G2", name = "G2 - scatter") %>%
  add_trace(df2_G2, x = df2_G2$x, y = df2_G2$y, color = I("green"),
            legendgroup = "G2", name = "G2 - line", mode = "lines") %>%
  add_trace(df1_G3, x = df1_G3$x, y = df1_G3$y, color = I("blue"),
            legendgroup = "G3", name = "G3 - scatter") %>%
  add_trace(df2_G3, x = df2_G3$x, y = df2_G3$y, color = I("blue"),
            legendgroup = "G3", name = "G3 - line", mode = "lines") %>%
  add_trace(df1_G4, x = df1_G4$x, y = df1_G4$y, color = I("orange"), 
            legendgroup = "G4", name = "G4 - scatter") %>%
  add_trace(df2_G4, x = df2_G4$x, y = df2_G4$y, color = I("orange"), 
            legendgroup = "G4", name = "G4 - line", mode = "lines")

Sample output

Showing the first group G1 deselected. Also note that the colours have been made to match between the scatter and line traces for the same group.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!