10/09/2021

Introduction

Data info

In this Shiny application, the mtcars data set was used. This application uses different variables to plot against the mpg (Miles per Gallon) variable, also draws a simple regression line of (hp ~ mpg).

head(mtcars)
##                    mpg cyl disp  hp drat    wt  qsec vs am gear carb
## Mazda RX4         21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
## Mazda RX4 Wag     21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
## Datsun 710        22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
## Hornet 4 Drive    21.4   6  258 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2
## Valiant           18.1   6  225 105 2.76 3.460 20.22  1  0    3    1

Ui.R code

library(shiny)

shinyUI(fluidPage(
    titlePanel("Cars Dataset - Miles per Gallon"),
  
  sidebarPanel(selectInput("var", "Variable:", 
                        c("Cylinders" = "cyl", "Transmission type" = "am",
                          "Gears" = "gear")),
            checkboxInput("model", "Show a simple regression model of hp vs mpg", 
                          value = FALSE),
                        submitButton("Sure! It seems cool")
        ),
  mainPanel(
            h3(textOutput("title")),
            plotOutput("plot1"),
            plotOutput("plot2")
  )
))

Sever.R code

library(shiny)
library(ggplot2)

data <- mtcars
data$am <- factor(data$am, labels = c("Auto", "Manual"))

shinyServer(function(input, output) {
    fig_title <- reactive({
        paste("mpg vs ", input$var)
    })
    output$title <- renderText({
        fig_title()
    })
    output$plot1 <- renderPlot({
        if(input$var == "cyl"){
            plot(mtcars$cyl, mtcars$mpg, main = "Plot of mpg vs cyl",
                 xlab = "Cylinders", ylab = "Miles Per Gallon (mpg)")
        }
        if(input$var == "am"){
        
            boxplot(mtcars$mpg, mtcars$am, names = c("Auto", "Manual"),
                    main = " Boxplot of mpg of each transmission type ")
        }
        if(input$var == "gear"){
            plot(mtcars$gear, mtcars$mpg,
                    main = " Plot of mpg of each gear", xlim = c(3, 5))
        }

    })
    output$plot2 <- renderPlot({
        if(input$model){
            model1 <- lm(hp~mpg, data = mtcars)
           
                plot(mtcars$mpg, mtcars$hp, xlab = "Miles per Gallon",
                     ylab = "Horsepower", bty = "n", pch = 16,
                     xlim = c(10,35), ylim = c(50, 350))
                abline(model1, col = "red", lwd = 2)
        }
        })
})