Creating Maps with ggplot2 Tutorial

Aug 5, 2024

Lecture Notes: Creating Maps with ggplot2

Introduction to ggplot2 Maps

  • Tip #13: Focus on creating maps with ggplot.
  • Importance of maps: Great visuals for publications and reports.
  • Key concepts: ggplot, map data, coordinate systems (latitude and longitude).
  • Example map: Voting patterns in the U.S. for the 1976 election.

Getting Started

  1. Sign Up: Register for weekly R tips.
  2. Access GitHub Repo: Perform a git pull to get all the code.
  3. Open File: Locate and open 01_03_ggplot2_maps.R.

Libraries to Load

  • Tidyverse: Core library for data manipulation and visualization.
  • Maps Library: Provides access to map data.
  • Map Projection Library: Ensures correct projection of maps.

Accessing Map Data

  • Use map_data() function from ggplot2 to get map datasets.
  • Plan to create a world map using this function.

Creating a World Map

  1. Load world map data using:
    world_map <- map_data("world")
    
  2. Visualize using ggplot:
    • Use geom_map() to create a blank canvas.
    • Map latitude and longitude with appropriate aesthetics (aes).
  3. Projection: Add coordinate system for accurate visual representation.
    • Use coord_map() to apply an orthogonal projection.

Focusing on the United States

  • Narrow down to U.S. states:
    usa_map <- map_data("state")
    
  • Visualize using ggplot similar to world map.
  • Ensure to add coordinate system for accuracy.

Integrating Data with Maps

  • Introduce the concept of combining map visuals with data.
  • Example: Republican voting data by state for 1976 election.

Data Wrangling Steps

  1. Access voting data from the maps library:
    vote_data <- map_data("vote_repub") 
    
  2. Filter for 1976 data:
    • Create a tibble, select necessary columns (state and 1976 results).
    • Rename columns and convert units to proportions.
  3. Join Data: Use left_join() to combine voting data with U.S. map data:
    voting_data <- left_join(usa_map, vote_data, by = "state")
    

Creating a Chloropleth Map

  • Use ggplot to visualize voting data:
    • Aesthetics:
      • aes(x = long, y = lat, group = group, fill = republican_proportion).
    • Add layers using geom_polygon() for states.
  • Customize color gradient:
    • Define color scale from dark blue (Democrat) to red (Republican).
    • Use scale_fill_gradient2() to set the midpoint color as white.

Final Adjustments

  • Theme customizations:
    • Use theme_minimal() to clean up the visual.
    • Add labels for clarity and context.
    • Adjust title and legend position.

Conclusion

  • Final output: A clear and visually appealing map showing voting patterns in 1976.
  • Encouragement to sign up for the R tips newsletter for further learning and resources.