Newer
Older
#' Visualize Mean Flight Delay by Airport
#'
#' This function visualizes the mean flight delay at each origin airport in the nycflights13 dataset.
#' It calculates the mean departure delay for each airport, joins this data with airport locations,
#' and creates a scatter plot showing mean delay as point size and color on a map of airport locations.
#'
#' @return A ggplot2 object representing the visualization of mean flight delays by airport.
#' @import dplyr
#' @import ggplot2
#' @import nycflights13
#' @examples
#' # Run the function to visualize mean delays by airport:
#' visualize_airport_delays()
#' @name visualize_airport_delays
#' @export
visualize_airport_delays <- function() {
# Join flights and airports datasets to include latitude and longitude
airport_delays <- nycflights13::flights %>%
dplyr::filter(!is.na(.data$dep_delay)) %>%
dplyr::group_by(.data$origin) %>%
dplyr::summarize(mean_delay = mean(.data$dep_delay, na.rm = TRUE)) %>%
dplyr::left_join(nycflights13::airports, by = c("origin" = "faa"))
ggplot2::ggplot(airport_delays, ggplot2::aes(x = .data$lon, y = .data$lat)) +
ggplot2::geom_point(ggplot2::aes(size = .data$mean_delay, color = .data$mean_delay), alpha = 0.9) +
ggplot2::scale_color_gradient(low = "blue", high = "red") +
ggplot2::labs(
title = "Mean Flight Delay by Airport",
x = "Longitude",
y = "Latitude",
size = "Mean Delay (min)",
color = "Mean Delay (min)"
) +
ggplot2::theme_minimal()