динамически добавлять графики на веб-страницу, используя блестящие

Я хочу создать приложение с использованием блестящего, которое динамически добавляет графики на страницу. это может быть 10 участков, а может быть только один. Я использую этот учебник на блестящей домашней странице для динамического пользовательского интерфейса.

это упрощенный пример. функция showme строит график

server.r

shinyServer(function(input, output) {
  # Create an environment for storing data
  symbol_env <- new.env()
  # Make a chart for a symbol, with the settings from the inputs
  make_chart <- function(symbol) {
    showme(symbol)
  }

  display <- c("1083484" , "1101732")

  output$MyList <- renderUi({ 
    for (i in i:nrow(display))
       renderPlot({make_chart(display[i])})
    })
})

ui.r

shinyUI(pageWithSidebar(
  headerPanel("My Plots !"),
  sidebarPanel(
    wellPanel(
      p(strong("Scan1"))))
 ,mainPanel(
      uiOutput("MyList")
)))

я получаю следующую ошибку

Listening on port 8100
Error in .subset2(x, "impl")$defineOutput(name, value, deparse(substitute(value))) : 
  Unexpected character output for display

если это не так - я был бы признателен за любые рекомендации. Спасибо.

> sessionInfo()
R version 2.15.3 (2013-03-01)
Platform: i386-w64-mingw32/i386 (32-bit)

person haki    schedule 08.04.2013    source источник


Ответы (3)


Возможно, вам будет полезен этот пример Уинстона Чанга:

Блестящий пример приложения с динамическим количеством графиков

Вот полный пример на всякий случай:

server.R

max_plots <- 5

shinyServer(function(input, output) {

# Insert the right number of plot output objects into the web page
output$plots <- renderUI({
  plot_output_list <- lapply(1:input$n, function(i) {
     plotname <- paste("plot", i, sep="")
     plotOutput(plotname, height = 280, width = 250)
   })

   # Convert the list to a tagList - this is necessary for the list of items
   # to display properly.
   do.call(tagList, plot_output_list)
})

# Call renderPlot for each one. Plots are only actually generated when they
# are visible on the web page.
for (i in 1:max_plots) {
    # Need local so that each item gets its own number. Without it, the value
    # of i in the renderPlot() will be the same across all instances, because
    # of when the expression is evaluated.
    local({
        my_i <- i
        plotname <- paste("plot", my_i, sep="")

        output[[plotname]] <- renderPlot({
        plot(1:my_i, 1:my_i, xlim = c(1, max_plots), ylim = c(1, max_plots), main = paste("1:", my_i, ".  n is ", input$n, sep = ""))
        })
    })
}
})

ui.R

shinyUI(pageWithSidebar(

  headerPanel("Dynamic number of plots"),

    sidebarPanel(
      sliderInput("n", "Number of plots", value=1, min=1, max=5)
    ),

    mainPanel(
      uiOutput("plots") # This is the dynamic UI for the plots
    )
))
person Rahul Savani    schedule 25.05.2013
comment
Спасибо, чувак - это то, что я искал. Мне удалось получить динамический список нарисованных графиков, но я хочу распечатать список объектов - каждый объект содержит заголовок, график и таблицу. ты знаешь, как я могу это сделать? - person haki; 25.05.2013
comment
Вы имеете в виду, что а) для каждого выбранного объекта вы хотите построить все три элемента (заголовок, график и таблица), или б) для каждого выбранного объекта, вы хотите затем выбрать, какой из этих трех объектов построить (или вы имеете в виду что-то другое)? - person Rahul Savani; 25.05.2013
comment
а - для каждого объекта я хочу заголовок, график и сводную таблицу. динамический интерфейс должен быть своего рода контейнером, а не просто сюжетом. Я пробовал добавлять таблицы в список тегов и в вывод, используя renderTable, но он отображает только последний добавленный - в моем случае это таблица. - person haki; 25.05.2013
comment
Хм, похоже, это не работает с ggplot, есть идеи? - person evolvedmicrobe; 07.05.2014
comment
@RahulSavani: Можете ли вы сделать max_plots реактивным значением вместо жестко запрограммированного? Спасибо - person TTT; 14.11.2014
comment
для построения ggplot2, - person Zhilong Jia; 05.01.2015
comment
@RahulSavani Мне нужно б. (здесь задан специальный вопрос: stackoverflow.com/questions/29790915/) - person Uri Barenholz; 03.05.2015
comment
@ tao.hong Вместо использования max_plots вы можете поместить весь цикл for в observe и использовать input$max_plots для реактивности - person Rodrigo Zepeda; 17.12.2015

Чтобы ответить на вопрос в комментарии выше, о том, как динамически возвращать список объектов (например, график, таблицу и текст), вы можете сгенерировать список соответствующих выходных данных, содержащихся в теге div в renderUI, который вы затем совпадают с соответствующими функциями рендеринга в цикле for. Например:

max_plots <- 5

shinyServer(function(input, output) {

# Insert the right number of plot output objects into the web page
output$plots <- renderUI({
  plot_output_list <- lapply(1:input$n, function(i) {
     plotname <- paste("plot", i, sep="")
     plottitle <- paste("plottitle", i, sep="")
     tablename <- paste("tablename", i, sep="")
     tags$div(class = "group-output",
       textOutput(plottitle, container = h3),
       plotOutput(plotname, height = 280, width = 250),
       tableOutput(tablename)
     )
   })

   # Convert the list to a tagList - this is necessary for the list of items
   # to display properly.
   do.call(tagList, plot_output_list)
})

# Call renderPlot for each one. Plots are only actually generated when they
# are visible on the web page.
for (i in 1:max_plots) {
    # Need local so that each item gets its own number. Without it, the value
    # of i in the renderPlot() will be the same across all instances, because
    # of when the expression is evaluated.
    local({
        my_i <- i
        plotname <- paste("plot", my_i, sep="")
        plottitle <- paste("plottitle", my_i, sep="")
        tablename <- paste("tablename", my_i, sep="")

        output[[plotname]] <- renderPlot({
        plot(1:my_i, 1:my_i, xlim = c(1, max_plots), ylim = c(1, max_plots), main = paste("1:", my_i, ".  n is ", input$n, sep = ""))
        })
        output[[plottitle]] <- renderText({paste("1:", my_i, ".  n is ", input$n, sep = "")
        })
        output[[tablename]] <- renderTable({table(x = 1:my_i, y = 1:my_i)
        })
    })
}
})

Надеюсь, это поможет!

person skasch    schedule 31.03.2015

Динамически добавляйте N графиков по своему усмотрению, используя блестящий:

runApp(
list(
ui = fluidPage(
  headerPanel('Tittle'),

  sidebarPanel(
    fileInput('file1', 'Choose File:'),
    textInput("target", label="Target", value="Choose target"),
    actionButton("addButton", "Go!"),
    p('The button start the code server'),
    p("This is UI")

  ),

  mainPanel(

    uiOutput("plots")
  )),
#SERVER
server = function(input, output) {     
  dataset <- eventReactive(input$addButton, {

    #Obtain the file and textinput
    inFile <- input$file1
    df <- read.csv(inFile$datapath)
    df$target <- input$target
    return(df)

  })

  output$plots <- renderUI({


    df <- dataset()
    n <- df$target[1]

    plot_output_list <- lapply(1:n, function(i) {

      plotname <- paste("plot", i, sep="")
      plotOutput(plotname, height = 580, width = 550)


    })


    do.call(tagList, plot_output_list)


  })
  observe({             

    for (i in 1:length()) {
      local({ 


        plotname <- paste("plot", i, sep="")

        output[[plotname]] <- renderPlot({

          #function_plot is the function generate plot
          function_plot()

        })
      })#endlocal
    }

  })
}
  )
)

https://github.com/ericbellet/recomendacion-modelos/blob/master/shiny/generate_rocSHINY.R

person Eric Gabriel Bellet Locker    schedule 22.05.2016