I have a small R script that loads in a comma-separated file with data and displays it as a scatterplot. I can also identify individual points of interest in the scatterplot by hovering over them with the mouse. This is cool but what I also want is to draw a rectangle over an area in the scatterplot, and get a list with the IDs of the data points within that rectangle. (The final goal of this is a shiny app).
I.e. how can I make it so that I can a) draw a rectangle, b) get the points within that rectangle and c) display that list for the end-user in a form that can be copied and pasted?
Here is a working example (using mtcars
instead of y csv-file):
library(ggvis)
mtc <- mtcars
mtc$id <- 1:nrow(mtc)
all_values <- function(x) {
if(is.null(x)) return(NULL)
row <- mtc[mtc$id == x$id, ]
paste0(names(row), ": ", format(row), collapse = "<br />")
}
mtc %>% ggvis(x = ~wt, y = ~mpg, key := ~id) %>%
layer_points() %>%
add_tooltip(all_values, "hover")
What you are (probably) looking for are the
plot_brush
-functions of theshiny
-package (you find an example here at the Shiny Gallery).The following will provide 2 apps, that are built on top of each other to answer your 3 questions:
1 Drawing a rectangle with plot_brush
This can be achieved with this code:
2 & 3 Identifying the points and printing a datatable
Using and extending part 1 we identify the points and load them into a data.frame called
res
and then load them into a datatable (using the 'DT'-package):This gives something like this:
This question on Stackoverflow will point you in the right direction for the mouseover.
Here's a simple example using the
locator()
function: