Home > database >  In Shiny/R how to control number of Ggplots charts displayed with SliderInput
In Shiny/R how to control number of Ggplots charts displayed with SliderInput

Time:08-28

I need to control the number of chart using a slideInput.

I have a list with ggplot charts. Once my slider came from 1 to 2 it will display the first 2 charts of this list. If the slider range is from 1:3 it will display the first 3 charts from this list chart.

This is what Ive done so far:

library(shiny)
library(gapminder)
library(highcharter)

df <- gapminder %>% group_split(country)

countries <- df[1:10] %>% set_names(1:10)

ggplots_list <- countries %>% map(~ .x %>% ggplot(aes(x = year, y = pop))   geom_line())

library(shiny)

ui <- fluidPage(
  
  
  sliderInput(inputId =  "slider_new",
              label = "Projections Range",
              width = '100%',
              min = 1, max = 10, 
              value = 1
  ) ,
  plotOutput('chart_1', height = '500px')
)

server <- function(input, output, session) {
  
  output$chart_1 <- renderPlot({
    ggplots_list[input$slider_new[1]]
    
    
  })
  
}

shinyApp(ui, server)

The idea is to have a grid of charts as I increase the slider value.

Any help?

CodePudding user response:

Try this

library(gapminder)
library(highcharter)
library(purrr)

df <- gapminder %>% group_split(country)

countries <- df[1:10] %>% set_names(1:10)

ggplots_list <- countries %>% map(~ .x %>% ggplot(aes(x = year, y = pop))   geom_line())

library(shiny)

ui <- fluidPage(
  
  
  sliderInput(inputId =  "slider_new",
              label = "Projections Range",
              width = '100%',
              min = 1, max = 10, 
              value = 1
  ) ,
  uiOutput("chart_1")
)

server <- function(input, output, session) {
  
  lapply(1:10, function(i){
    output[[paste0("plots",i)]] <- renderPlot({ ggplots_list[i] })
  })
  
  output$chart_1 <- renderUI({
    n <- input$slider_new
    lapply(1:n, function(i) plotOutput(paste0("plots",i), height=500))
  })
  
}

shinyApp(ui, server)
  • Related