Reputation: 17676
how can I select a subset of the data and plot it using shiny
& ggvis
?
As the ggvis documentation states, it is not possible to swap the dataset using ggvis
input_select
. Besides this limitation it would be awesome if the data preprocessing & filtering would have to be performed only once.
This is my try using selectInput()
. I want to be able to choose parts or the whole dataset for display
library(ggvis)
library(dplyr)
set.seed(1233)
cocaine <- cocaine[sample(1:nrow(cocaine), 500), ]
shinyServer(function(input, output, session) {
output$choose_dataset <- renderUI({
selectInput("dataset", "Select", append("Give me all!", as.list(sort(unique(cocaine$state)))))
})
if(input$dataset != "Give me all!"){
a <- filter(rawData, cocaine$state == input$dataset)
}
if(input$dataset == "Give me all!"){
a <- cocaine
}
a$id <- 1:nrow(a)
return(a)
datFiltered %>%
ggvis(~weight, ~price, key := ~id) %>%
bind_shiny("plot1") # Very important!
})
Here is the UI
library(ggvis)
shinyUI(bootstrapPage(
uiOutput("choose_dataset"),
ggvisOutput("plot1")
))
Upvotes: 1
Views: 763
Reputation: 31
@daattali - I have a suggested improvement to your solution. You use filter in the observeEvent, which introduces NA's to the solution and causes the event to fire incorrectly. Instead, use subset as shown below:
runApp(shinyApp(
ui = fluidPage(
uiOutput("choose_dataset"),
ggvisOutput("plot1")
),
server = function(input, output, session) {
output$choose_dataset <- renderUI({
selectInput("dataset", "Select", append("Give me all!", as.list(sort(unique(cocaine$state)))))
})
observeEvent(input$dataset, {
if(input$dataset == "Give me all!"){
data <- cocaine
} else {
data <- subset(cocaine, cocaine$state == input$dataset)
}
data$id <- seq(nrow(data))
data %>%
ggvis(~weight, ~price, key := ~id) %>%
layer_points() %>%
bind_shiny("plot1")
})
}
))
Upvotes: 2
Reputation: 26323
Your code has a few problems and doesn't run... why are you returning from the main server function? And you're using two variables dataFiltered
and rawData
that aren't defined anywhere.
Here is the solution of what you're trying to do
runApp(shinyApp(
ui = fluidPage(
uiOutput("choose_dataset"),
ggvisOutput("plot1")
),
server = function(input, output, session) {
output$choose_dataset <- renderUI({
selectInput("dataset", "Select", append("Give me all!", as.list(sort(unique(cocaine$state)))))
})
observeEvent(input$dataset, {
if(input$dataset == "Give me all!"){
data <- cocaine
} else {
data <- filter(cocaine, cocaine$state == input$dataset)
}
data$id <- seq(nrow(data))
data %>%
ggvis(~weight, ~price, key := ~id) %>%
layer_points() %>%
bind_shiny("plot1")
})
}
))
Please try to post code that can be run or at least make in the code saying what doesn't run or what variables need to be defined etc :)
Upvotes: 3