#######  Installing and loading required packages ####### 

if (!require("tidyverse")) install.packages("tidyverse")
if (!require("RColorBrewer")) install.packages("RColorBrewer")

library(tidyverse)
library(RColorBrewer)

# Reading the data

counties <- read.csv("https://github.com/drkblake/Data/raw/refs/heads/main/counties.csv")

# The basics

ggplot(counties, aes(x = Broadband,
                     y = Income)) +
  geom_point() +
  labs(x = "Broadband access",
       y = "Income",
       color = "Urbanization",
       title = "Worker income",
       caption = "Source: U.S. Census Bureau")

ggplot(counties, aes(x = Broadband,
                     y = Income,
                     color = Urban3)) +
  geom_point() +
  labs(x = "Broadband access",
       y = "Income",
       color = "Urbanization",
       title = "Worker income",
       caption = "Source: U.S. Census Bureau") +
  scale_color_brewer(palette = "Dark2")

# Modifiying basic properties of the plot
  
ggplot(counties, aes(x = Broadband,
                       y = Income)) +
    geom_point(color = "red",
               size = 2,
               alpha = .3,
               shape = "square") +
    labs(x = "Broadband access",
         y = "Income",
         color = "Urbanization",
         title = "Worker income",
         caption = "Source: U.S. Census Bureau")

# Adding another layer

ggplot(counties, aes(x = Broadband,
                     y = Income)) +
  geom_point() +
  geom_smooth(method = "lm",
              se = FALSE) +
  labs(x = "Broadband access",
       y = "Income",
       color = "Urbanization",
       title = "Worker income",
       caption = "Source: U.S. Census Bureau")

ggplot(counties, aes(x = Broadband,
                     y = Income,
                     color = Urban3)) +
  geom_point() +
  geom_smooth(method = "lm",
              se = FALSE) +
  labs(x = "Broadband access",
       y = "Income",
       color = "Urbanization",
       title = "Worker income",
       caption = "Source: U.S. Census Bureau") +
  scale_color_brewer(palette = "Dark2")

# Other plots

ggplot(counties, aes(x = Income)) +
  geom_histogram(bins = 15)

ggplot(counties, aes(x = Income)) +
  geom_freqpoly(bins = 15)

ggplot(counties, aes(x = Urban3)) +
  geom_bar(color = "black",
           fill = "lightblue")

ggplot(counties, aes(x = Urban3,
                     fill = Urban3)) +
  geom_bar(show.legend = FALSE) +
  scale_fill_brewer(palette = "Dark2")

ggplot(counties, aes(x = Urban3,
                     y = Income,
                     color = Urban3)) +
    geom_boxplot(show.legend = FALSE) +
    scale_color_brewer(palette = "Dark2") +
    theme_minimal()

# Faceting

ggplot(counties, aes(x = Income,
                     fill = Urban3)) +
  geom_histogram(bins = 15,
                 show.legend = FALSE) +
  facet_wrap(~Urban3,
             ncol = 1) +
  scale_fill_brewer(palette = "Dark2")