从同一模型渲染R Shiny中的多个图

时间:2018-11-26 15:19:43

标签: r shiny

在R Shiny中,我试图从一个模型(包括一组模拟)生成多个图,但它仅返回一个图。我从another post on stack overflow中的答案尝试了代码,但是它有效,但是当我在模型中添加第二个图时,只能显示第二个图,而不能显示第一个图。有人可以对此提出建议吗?来自上面提到的帖子中答案的代码如下:

library(shiny)

ui <- shinyUI(fluidPage(
br(),
actionButton("numb", "generate a random numbers"),
br(),
br(),
verbatimTextOutput("text"),
plotOutput("plot"),
plotOutput("plot2"),
tableOutput("table")
))

server <- shinyServer(function(input, output) {

model <- eventReactive(input$numb, {
# draw a random number and print it
random <- sample(1:100, 1)
print(paste0("The number is: ", random))

# generate data for a table and plot
data <- rnorm(10, mean = 100)
table <- matrix(data, ncol = 2)

# create a plot 
Plot <- plot(1:length(data), data, pch = 16, xlab ="This is the first plot", ylab = 
"")

# create a second plot
Plot2 <- plot(1:length(data), data, pch=16, xlab="This is the second plot", ylab = 
"")

# return all object as a list
list(random = random, Plot = Plot, Plot2=Plot2, table = table)
})

 output$text <- renderText({
# print the random number after accessing "model" with brackets.
# It doesn't re-run the function.
youget <- paste0("After using model()$random you get: ", model()$random,
                 ". Compare it with a value in the console")
print(youget)
youget
 })

 output$plot <- renderPlot({
  # render saved plot
  model()$Plot
 })

 output$plot2 <-renderPlot({
  # render second plot
   model()$Plot2

 })

 output$table <- renderTable({

  model()$table
  })
  })


   shinyApp(ui = ui, server = server)

1 个答案:

答案 0 :(得分:0)

我将图移至renderPlot服务器函数并修改了图调用:

server <- shinyServer(function(input, output) {

  model <- eventReactive(input$numb, {
    # draw a random number and print it
    random <- sample(1:100, 1)
    print(paste0("The number is: ", random))

    # generate data for a table and plot
    data <- rnorm(10, mean = 100)
    table <- matrix(data, ncol = 2)

    # return all object as a list
    list(random = random, table = table)
  })

  output$text <- renderText({
    # print the random number after accessing "model" with brackets.
    # It doesn't re-run the function.
    youget <- paste0("After using model()$random you get: ", model()$random,
                     ". Compare it with a value in the console")
    print(youget)
    youget
  })

  output$plot <- renderPlot({
    # render saved plot
    mod_list=model()
    data=mod_list$table
    # create a plot
    plot(data[,1], data[,2], pch = 16, xlab ="This is the first plot", ylab ="")

  })

  output$plot2 <-renderPlot({
    # render second plot
    mod_list=model()
    data=mod_list$table
    # create a second plot
    plot(data[,1], data[,2], pch=16, xlab="This is the second plot", ylab ="")

  })

  output$table <- renderTable({

    model()$table
  })
})

您的plot函数的x和y参数令人困惑。如果每个图要两条线,请尝试使用qplot和melt函数将数据框重整为长格式。如果您只想包含10个随机值的绘图,请不要使用矩阵函数