我正在ggplot
应用中将一些ggvis
/ plotly
个地图迁移到shiny
。关于链接的链接,我遇到了一个问题。我希望能够通过group
在相关数据框之间共享的# 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)
显示/隐藏跟踪。
showlegend = FALSE
我的在线搜索,特别是阅读plotly文档并没有把我带走。
我可以将group
添加到第二个跟踪中。这确实有助于解决这一挑战,但是,我仍然希望根据plotly
值显示/隐藏该跟踪。
基于group
的体系结构,似乎如果我可以将散布和线放到每个group
的一个跟踪上,那么我会得到所需的行为。但是,似乎跟踪可能只有一个“模式”,这就是为什么我采用了我的方法。
如果我沿着我开始的路走下去,我想我需要以某种方式陷入传奇的“点击”事件并显示/隐藏colors
痕迹...但我不是真的确定从哪里开始。
在我的MWE中,我将viridis
参数设置为group
。虽然这对问题不重要,但我没有找到确保颜色选择链接到group
的方法(即如果df1上的group
的跟踪是蓝色的,我想制作df2的跟踪上有相同的{{1}}蓝色。如果这是非平凡的并且保证第二个问题(我搜索并发现没有匹配......可能因为它是微不足道的,我错过了一些简单的东西),那么我我会分开问这个部分。
答案 0 :(得分:2)
自首次提出此问题以来,legendgroup
和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")
对此进行了一些更改。在当前版本(4.7.1)中,有一个参数G1
可以解决问题。
请原谅优雅编码所付出的最小努力,但是,MWE的这一扩展演示了按组显示/隐藏痕迹的能力。
{{1}}
显示取消选择的第一个组{{1}}。另请注意,已使颜色在同一组的散点图和线迹之间匹配。