|
| 1 | +library(shiny) |
| 2 | + |
| 3 | +# Define UI for application that draws a Load-velocity plot |
| 4 | +ui <- fluidPage( |
| 5 | + # Application title |
| 6 | + titlePanel("Load-velocity Model"), |
| 7 | + |
| 8 | + # Sidebar with input fields for speed and charge |
| 9 | + sidebarLayout( |
| 10 | + sidebarPanel( |
| 11 | + numericInput("speed", "Enter Speed (m/s):", value = 0, min = 0), |
| 12 | + numericInput("charge", "Enter Charge (kg):", value = 0, min = 0), |
| 13 | + actionButton("add", "Add to Plot"), |
| 14 | + actionButton("clear", "Clear Plot") |
| 15 | + ), |
| 16 | + |
| 17 | + # Show a plot of the generated model |
| 18 | + mainPanel( |
| 19 | + plotOutput("lvPlot") |
| 20 | + ) |
| 21 | + ) |
| 22 | +) |
| 23 | + |
| 24 | +# Define server logic required to draw the plot |
| 25 | +server <- function(input, output) { |
| 26 | + # Data storage |
| 27 | + data <- reactiveVal(data.frame(speed = numeric(0), charge = numeric(0))) |
| 28 | + |
| 29 | + observeEvent(input$add, { |
| 30 | + new_data <- data() |
| 31 | + new_data <- rbind(new_data, data.frame(speed = input$speed, charge = input$charge)) |
| 32 | + data(new_data) |
| 33 | + }) |
| 34 | + |
| 35 | + observeEvent(input$clear, { |
| 36 | + data(data.frame(speed = numeric(0), charge = numeric(0))) |
| 37 | + }) |
| 38 | + |
| 39 | + output$lvPlot <- renderPlot({ |
| 40 | + plot_data <- data() |
| 41 | + plot(plot_data$charge, plot_data$speed, |
| 42 | + xlab = "Charge (kg)", ylab = "Speed (m/s)", |
| 43 | + main = "Load-velocity Model", pch = 19) |
| 44 | + if(nrow(plot_data) > 1) { |
| 45 | + # Add regression line |
| 46 | + fit <- lm(speed ~ charge, data = plot_data) |
| 47 | + abline(fit, col = "blue") |
| 48 | + |
| 49 | + # Optionally, add the regression equation to the plot |
| 50 | + eq <- paste0("y = ", round(coef(fit)[1], 2), " + ", round(coef(fit)[2], 2), "x") |
| 51 | + legend("topleft", legend = eq, bty = "n") |
| 52 | + } |
| 53 | + }) |
| 54 | +} |
| 55 | + |
| 56 | +# Run the application |
| 57 | +shinyApp(ui = ui, server = server) |
0 commit comments