Assignment 7

library(dslabs)
library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.2.1     ✔ readr     2.2.0
✔ forcats   1.0.1     ✔ stringr   1.6.0
✔ ggplot2   4.0.3     ✔ tibble    3.3.1
✔ lubridate 1.9.5     ✔ tidyr     1.3.2
✔ purrr     1.2.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
data("murders")
head(murders) 
       state abb region population total
1    Alabama  AL  South    4779736   135
2     Alaska  AK   West     710231    19
3    Arizona  AZ   West    6392017   232
4   Arkansas  AR  South    2915918    93
5 California  CA   West   37253956  1257
6   Colorado  CO   West    5029196    65
data(package = "dslabs") 
heatmap_data <- murders %>%
  mutate(
    pop_group = cut(
      population,
      breaks = c(0, 2000000, 5000000, 10000000, Inf),
      labels = c("Under 2 million", "2-5 million",
                 "5-10 million", "10+ million"),
      right = FALSE
    )
  ) %>%
  
  
  group_by(region, pop_group) %>%
  
 
  summarise(
    murder_rate = sum(total) / sum(population) * 100000,
    .groups = "drop"
  ) 
ggplot(heatmap_data,
       aes(x = region, y = pop_group, fill = murder_rate)) +
  
  
  geom_tile(color = "white", linewidth = 1) +
  

  scale_fill_gradient(
    low = "lightblue",
    high = "darkblue",
    name = "Gun Murders\nper 100,000"
  ) +
  
  
  labs(
    title = "Gun Murder Rates by Region and Population (2010)",
    x = "U.S. Region",
    y = "State Population (People)",
    caption = "Source: DS Labs"
  ) +
  
  
  theme_minimal()

For my multivariable graph, I used the murders dataset from the dslabs package, which contains information about gun murders in the United States in 2010. The variables I used were region, population, and total gun murders. I created a heatmap by grouping states into population categories and calculating gun murder rates per 100,000 people. I used ggplot()and geom_tile() to create the graph, with lighter blue representing lower murder rates and darker blue representing higher rates. One pattern the graph shows is that gun murder rates vary across regions and population sizes, with some groups having higher rates than others. My graph is different from the examples in the class notes because I used a heatmap to compare regions, population categories, and gun murder rates instead of a traditional bar graph or scatterplot.