I use the mtcars
dataset as an example.
library(tidyverse)
library(plotly)
plot <- mtcars %>%
ggplot() +
geom_histogram(aes(mpg), binwidth = 3)
ggplotly(plot)
What I would like to do is to have a filter on, e.g. the am
variable so I can easily update the plots so the plot only shows the same histograms
but only for only am==1
etc. So I would like a button on the graph so I can make the filter.
Well this works:
library(plotly)
mtcars %>%
plot_ly(x = ~mpg ) %>%
add_histogram(frame=~am)
"frame" creates a slider...
Here is a solution with shiny
:
library(shiny)
ui <- fluidPage(
checkboxGroupInput("cols", label = "Columns", choices = unique(mtcars$cyl), selected = unique(mtcars$cyl)[1] ),
plotOutput("plot")
)
server <- function(input, output, session) {
output$plot <- renderPlot({
data <- mtcars
data <- data[data$cyl %in% input$cols,]
hist(data$mpg)
})
}
shinyApp(ui, server)