简体   繁体   中英

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

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM