Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about passing data frame between functions with RStudio's Shiny

Tags:

r

shiny

I would like two plots to appear. First, a scatter plot and then a line graph. The graphs aren't important. This is my first time using Shiny. What is the best way to have both

  plotOutput("needles"),
  plotOutput("plot")

use the data from the same needles data frame? I think I'm getting confused as to how to pass the "needles" data frame between the plotOutput functions.

library(shiny)
library(tidyverse)
library(scales)

# Create the data frame ________________________________________________
create_data <- function(num_drops) {
  needles <- tibble (
    x = runif(num_drops, min = 0, max = 10),
    y = runif(num_drops, min = 0, max = 10)
  )
}

# Show needles ________________________________________________
show_needles <- function(needles) {
 ggplot(data = needles, aes(x = x, y = y)) + 
    geom_point()

}

# Show plot __________________________________________________
show_plot <- function(needles) {
  ggplot(data = needles, aes(x = x, y = y)) + 
    geom_line()
}

# Create UI
ui <- fluidPage(

  sliderInput(inputId = "num_drops", 
              label = "Number of needle drops:",
              value = 2, min = 2, max = 10, step = 1),

  plotOutput("needles"),
  plotOutput("plot")

)

server <- function(input, output) {

  output$needles <- renderPlot({
    needles <- create_data(input$num_drops)
    show_needles(needles)
  })

  output$plot <- renderPlot({
    show_plot(needles)
  })
}

shinyApp(ui = ui, server = server)
like image 642
ixodid Avatar asked Nov 29 '25 04:11

ixodid


1 Answers

We could execute the create_data inside a reactive call in the server and then within the renderPlot, pass the value (needles()) as arguments for show_needles and show_plot

server <- function(input, output) {

  needles <- reactive({
     create_data(input$num_drops)

  })
  output$needles <- renderPlot({

    show_needles(needles())
  })

  output$plot <- renderPlot({

    show_plot(needles())
  })
}

shinyApp(ui = ui, server = server)

-output

enter image description here

like image 83
akrun Avatar answered Nov 30 '25 19:11

akrun