Assignment 6 - October 31st, 2025

In Class Coding Competition 3:

This is the shiny application that allows users to toggle between a bubble chart and a line histogram showcasing the relationship between the MPG of a vehicle and its weight, frequency polygon, horsepower, and bin width.

This is the code to our application.

# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
#    https://shiny.posit.co/
library(shiny)
library(ggplot2)

# Define UI for application
ui <- fluidPage(
  titlePanel("mtcars: Distribution and Relationship Visualization"),
  
  sidebarLayout(
    sidebarPanel(
      # Select which plot to display
      selectInput("plot_type", "Choose Visualization:",
                  choices = c("Line Histogram (MPG)" = "histogram",
                              "Bubble Chart" = "bubble")),
      
      # Conditional UI for the histogram
      conditionalPanel(
        condition = "input.plot_type == 'histogram'",
        sliderInput("bins", "Bin Width for Line Histogram:",
                    min = 1, max = 5, value = 2, step = 0.5)
      )
    ),
    
    mainPanel(
      plotOutput("mainPlot")
    )
  )
)

# Define server logic
server <- function(input, output) {
  
  output$mainPlot <- renderPlot({
    
    data <- mtcars #sample dataset from shiny library
    
    if (input$plot_type == "histogram") {
      # Line Histogram (Frequency Polygon) for MPG
      ggplot(data, aes(x = mpg)) +
        geom_freqpoly(
          binwidth = input$bins,
          color = "darkgreen",
          linewidth = 1.2
        ) +
        labs(
          title = "Frequency Polygon of Car Mileage (MPG)",
          x = "Miles Per Gallon (mpg)",
          y = "Count"
        ) +
        theme_minimal()
      
    } else if (input$plot_type == "bubble") {
      # Bubble Chart: X=Weight, Y=MPG, Size=Horsepower
      ggplot(data, aes(x = wt, y = mpg, size = hp, color = as.factor(cyl))) +
        geom_point(alpha = 0.7) +
        scale_size_continuous(range = c(3, 15)) + # Scale bubble size for better visibility
        labs(
          title = "Bubble Chart: MPG vs. Weight",
          x = "Weight (1000 lbs)",
          y = "Miles Per Gallon (mpg)",
          size = "Horsepower (hp)",
          color = "Cylinders"
        ) +
        theme_bw()
    }
  })
}

# Run the application 
shinyApp(ui = ui, server = server)