Reputation: 185
I have the following ggvis with shiny code, which produces 2 graphs with the mtcars data set that comes with R. In the first graph if I double click on a point, all the points with the same number of gear (mtcars$gear) within the 2nd graph turns into red. Motor cars can have 3, 4 or 5 gears. So, if I click on a point in the 1st graph, which has 3 gears, all the cars which have 3 gears turn into red points in the 2nd graph.
This is the server.R code-
library(ggvis)
library(dplyr)
mtcars$id <- seq_len(nrow(mtcars))
shinyServer(function(input, output, session) {
lb <- linked_brush(keys = mtcars$id, "red")
mtcars %>%
ggvis(~mpg, ~wt) %>%
layer_points(fill := lb$fill, fill.brush := "red") %>%
lb$input() %>%
set_options(width = 300, height = 300) %>%
bind_shiny("plot1") # Very important!
# A subset of mtcars, of only the selected points
selected <- lb$selected
mtcars_selected <- reactive({
mtcars[selected(), ]
})
mtcars_selected1 <- reactive({
print(mtcars[mtcars$gear == mtcars[selected(), ]$gear, ])
})
vis <- reactive({
mtcars %>%
ggvis(~mpg, ~wt) %>%
layer_points() %>%
add_data(mtcars_selected1) %>%
layer_points(fill := "#dd3333") %>%
set_options(width = 300, height = 300)
})
vis %>% bind_shiny("plot2")
})
This is the ui.R code -
library(ggvis)
shinyUI(bootstrapPage(
ggvisOutput("plot1"),
ggvisOutput("plot2")
))
My question is, is it possible to do this in the same graph ? That is I want to click on a point and all the points with the same number of gears will turn into red in the same graph. I have googled it for a long time and I cant seem to find any direction. Any help will be greatly appreciated.
Upvotes: 2
Views: 502
Reputation: 21425
You can add another layer in the first plot that will add the points that have the same gears as the selected points:
mtcars %>%
ggvis(~mpg, ~wt) %>%
layer_points(fill := lb$fill, fill.brush := "red") %>%
lb$input() %>%
set_options(width = 300, height = 300) %>%
#the next line will add red points that have the same gear as the ones selected
layer_points(fill := "red", data = reactive(mtcars[mtcars$gear %in% mtcars[lb$selected(),]$gear,])) %>%
bind_shiny("plot1") # Very important!
Upvotes: 1