问题
我正在将一些ggplot / ggvis图转移到一个闪亮的应用程序中.关于链接的链接,我遇到了一个问题.我希望能够在相关数据框之间共享的图例上按组显示/隐藏跟踪.
最小的工作示例
# load libraries
library(dplyr)
library(plotly)
library(viridis)
# contrived data to represent actual data points
df1 <- data.frame(x = rnorm(100),
y = rnorm(100),
group = rep(c("G1", "G2", "G3", "G4"), 25))
# contrived data to represent theoretical relationship
df2 <- data.frame(x = c(rep(-2, 4), rep(2, 4)),
y = c(seq(1.9, 1, -0.3), seq(-1, -1.9, -0.3)),
group = rep(c("G1", "G2", "G3", "G4"), 2))
# create plot with scatter and line traces
df1 %>%
plot_ly(x = x,
y = y,
color = group,
colors = viridis(n_distinct(group)),
mode = "markers") %>%
add_trace(x = x,
y = y,
color = group,
colors = viridis(n_distinct(group)),
mode = "lines",
data = df2)
到目前为止的尝试
我的在线搜索,特别是阅读plotly文档并没有把我带走.
我可以将showlegend = FALSE添加到第二个跟踪.这确实有助于解决这一挑战,但是,我仍然希望根据组值显示/隐藏该跟踪.
可能的解决方案
基于plotly的体系结构,似乎如果我可以将散布和线放到每个组的一个跟踪上,那么我将获得所需的行为.但是,似乎跟踪可能只有一个“模式”,这就是为什么我采用了我的方法.
如果我沿着我开始的路径继续下去,我想我需要以某种方式捕获图例的“on click”事件并显示/隐藏组跟踪…但我不确定从哪开始.
相关/中学
在我的MWE中,我将颜色参数设置为viridis.虽然这对问题不重要,但我没有找到确保颜色选择链接到组的方法(即如果df1上的组的跟踪是蓝色,我想在跟踪上为df2创建相同的组蓝色如果这是非平凡的,并保证第二个问题(我搜索并发现没有匹配……可能因为它是微不足道的,我遗漏了一些简单的东西),那么我将分别问这个部分.
最佳答案 为后代重温历史
首次询问ggplot2的几处变化,并在此问题之后的间隔时间内略有变化.在当前版本(4.7.1)中,有一个参数图例组可以解决问题.
懒惰的代码
请原谅优雅编码的最小努力,然而,MWE的这一扩展演示了按组显示/隐藏跟踪的能力.
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")
样本输出
显示第一组G1取消选择.另请注意,已使颜色与同一组的散点和线迹相匹配.