0

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.

xhr489
  • 1,957
  • 13
  • 39

2 Answers2

1

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)
xhr489
  • 1,957
  • 13
  • 39
  • Thank you David! is it possible to do exactly like this, but instead of slider add checkboxes ( or smth that can let you choose more than 1 input)? – yuliaUU May 16 '20 at 03:29
  • @yuliaUU. I just saw your reply now. Is your question still relevant? – xhr489 Jul 07 '20 at 12:00
  • Yes, please! I am still curious – yuliaUU Jul 07 '20 at 15:36
  • @yuliaUU. I will try to solve it. But just for you information this is a shiny problem and plotly is not enough, well at least this is my conclusion. Also I have seen an online book with shiny called "mastering shiny". – xhr489 Jul 08 '20 at 16:15
  • Yes, i was just curious cause I am working with him reports that are not published. I have coded the way to have interactivity of the shiny without using it, but there is only couple of issues (eg I now how to do a check list that will update the graph, but at first none of the checkbooks are checked, although the graph shows all data points. But apart from it, everything works well – yuliaUU Jul 08 '20 at 16:25
  • @yuliaUU: Se the answer. Can you use this? – xhr489 Jul 08 '20 at 18:23
0

@David I think what @marco means with a trigger in the code is something like:

 plot <- mtcars %>% 
  filter(am == 1) %>% 
  ggplot() + 
  geom_histogram(aes(mpg), binwidth = 3) +
  facet_wrap(~cyl) 

you can just provide a simple dplyr:filter, before you start creating the plot , this does not give you a button though.

Does this solve your issue?