【问题标题】:Rendering points() function on plot in Shiny app在 Shiny 应用程序的绘图上渲染 points() 函数
【发布时间】:2018-08-29 20:03:14
【问题描述】:

我正在尝试制作一个在图表顶部绘制点的 Shiny 应用程序。我不确定如何使绘图和点同时可见,因为似乎只使用了最后一个 renderPlot()。

我怎样才能同时绘制两者?

library(shiny)

server <- function(input, output, session) {          
  # data
  x <- c(1,3,4,6,2,4,6,8,6,3)
  y <- c(4,5,2,4,2,1,2,5,7,8)
  df <- data.frame(x,y)

  # plot
  output$plot <- renderPlot(plot(df[[1]],df[[2]]))        
  output$plot <- renderPlot(points(rnorm(200), rnorm(200)))
}

ui <- fluidPage(
  plotOutput("plot")
)

shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    您可以将数据存储在reactiveValues() 中。然后更新并绘制反应值数据。

    完整的可重现示例如下:

    library(shiny)
    
    x <- c(1, 3, 4, 6, 2, 4, 6, 8, 6, 3)
    y <- c(4, 5, 2, 4, 2, 1, 2, 5, 7, 8)
    
    server <- function(input,  output,  session) {          
      global <- reactiveValues(data = data.frame(x,  y))
    
      observeEvent(input$add,{
        global$data <- rbind(global$data, data.frame(x = rnorm(20), y = rnorm(20)))
      })
    
      output$plot <- renderPlot(plot(global$data$x, global$data$y))
    }
    
    ui <- fluidPage(
      actionButton("add", "Add"),
      plotOutput("plot")
    )
    
    shinyApp(ui = ui, server = server)
    

    【讨论】:

      【解决方案2】:

      我知道这是一个老问题,但我自己只是想知道它并想出了一个不同的解决方案。

      您可以通过list()plot()points() 通话放在一起。我决定用红色标出这些点以帮助区分。

      library(shiny)
      
      server <- function(input, output, session) {          
        # data
        x <- c(1,3,4,6,2,4,6,8,6,3)
        y <- c(4,5,2,4,2,1,2,5,7,8)
        df <- data.frame(x,y)
        
        # plot                    # use the list() function to put them together
        output$plot <- renderPlot(list(plot(df[[1]],df[[2]],
                                            points(rnorm(200), rnorm(200), col = 2)
                                            )
                                       )
        )
      }
      
      ui <- fluidPage(
        plotOutput("plot")
      )
      
      shinyApp(ui = ui, server = server)
      

      【讨论】:

        猜你喜欢
        • 2018-07-08
        • 2016-05-28
        • 2022-01-06
        • 1970-01-01
        • 2019-11-09
        • 2021-10-26
        • 2020-04-04
        • 2021-07-29
        • 2020-05-21
        相关资源
        最近更新 更多