I'm trying to implement shiny and ggvis for the first time.
I want to add a simple slider to filter for mpg in the mtcars dataset.
server.R
library(shiny)
library(ggvis)
library(dplyr)
data("mtcars")
shinyServer(function(input, output){
filtercar <- reactive({
mpgs <- input$mpg
m <- mtcars %>%
filter(
mpg >= mpgs
)
m <- as.data.frame(m)
})
mtcars %>%
ggvis(~mpg, ~disp, fill := "red") %>%
layer_points() %>%
bind_shiny("p", "p_ui")
})
ui.R
library(ggvis)
library(shiny)
shinyUI(bootstrapPage(
wellPanel(ggvisOutput("p"),
uiOutput("p_ui"),
HTML("Comparing cars by disp and mpg")),
wellPanel(HTML("CARS")),
wellPanel(
h4("Filter"),
sliderInput("mpg","miles per gallon", value = 20, min = 0, max = 100, step =
1)
)
))
Try this:
ui.R:
library(ggvis)
library(shiny)
shinyUI(bootstrapPage(
wellPanel(
uiOutput("p_ui"),
ggvisOutput("p"),
HTML("Comparing cars by disp and mpg")
)))
server.R:
library(shiny)
library(ggvis)
library(dplyr)
shinyServer(function(input, output) {
mtcars %>%
ggvis(~mpg, ~disp) %>%
filter(mpg > eval(input_slider(10, 35, 10))) %>% # this is the trick
layer_points() %>%
scale_numeric("x", domain = c(10, 35)) %>% # keep axis stable
scale_numeric("y", domain = c(0, 500)) %>% # same
bind_shiny("p", "p_ui")
})
So the trick is to use the filter
function from dplyr
together with eval
and the input_slider
function from ggvis
.