Creating a Map Using ggplot2

MTH 209 Data Manipulation and Management

Ying-Ju Tessa Chen

Department of Mathematics, University of Dayton

Overview

A map connects a geographic region to information about that region.

We will follow the original sequence:

  • World map and selected countries
  • World choropleth
  • U.S. states and interactive maps
  • Ohio counties
  • Bubble map

Packages and Map Data

Packages

library(tidyverse)
library(maps)
library(viridis)


Boundary data

map_data(map, region = ".", exact = FALSE, ...)

The drawing ingredients

Field Role
long, lat Boundary coordinates
group Separate polygons and islands
region Country or state name
  • ggplot2::map_data() retrieves boundaries from the maps package.
  • Use "world", "state", or "county" to choose the database.
  • region selects a subset.
  • exact = FALSE treats it as a pattern;
  • exact = TRUE requests an exact database-name match.

Later, usmap supplies geometry for geom_sf().

Drawing Boundaries with geom_polygon()

Coordinates form polygons

ggplot(map, aes(long, lat, group = group)) +
  geom_polygon(
    fill = "lightblue",
    colour = "white",
    linewidth = 0.15
  )


geom_polygon() connects each group of boundary vertices and closes its outline. Keep the vertices in their original order.

The new mapping arguments

Code Meaning
long, lat Longitude and latitude of boundary vertices
group = group Which vertices belong to each separate polygon
fill Interior color
colour Boundary color
linewidth Boundary thickness


Why group matters: islands can be separate polygons within the same country. Grouping only by country can connect unrelated pieces.

A Simple World Map

map <- map_data("world")

world_plot <- ggplot(
  map, aes(long, lat, group = group)) +
  geom_polygon(fill = "lightblue",
               colour = "white",
               linewidth = 0.15) +
  coord_quickmap() +
  theme_void()

world_plot

  • coord_quickmap() adjusts the aspect ratio for an approximate longitude/latitude map. It does not calculate a full map projection.
  • theme_void() removes axes, ticks, and the background grid.

A Map for Specific Regions

East_Asia <- c(
  "China", "Japan", "Mongolia", "North Korea", 
  "South Korea", "Taiwan"
)

East_Asia_map <- map %>%
  filter(region %in% East_Asia)

region_data <- East_Asia_map %>%
  group_by(region) %>%
  summarise(long = mean(long),
            lat = mean(lat)) %>%
  mutate(label_color = if_else(
    region %in% c("China", "Japan", "Mongolia"),
    "white", "black"))

Selected boundaries

The mean boundary coordinates give approximate label locations. These are not geographic centroids.

Map Labels and Color Scales

A separate dataset for labels

geom_text(
  data = region_data,
  aes(label = region, colour = label_color)
) +
scale_colour_identity()


Boundary data contain many rows per region.


  • region_data has one label position per region, so the layer prints each name once.
  • scale_colour_identity() uses stored color values such as "white" directly.

Discrete and continuous colors

Function Appropriate values
scale_fill_viridis_d() Categories, such as country names
scale_fill_viridis_c() Numbers, such as litres per person


  • option selects a palette, for example "B" or "H". It changes the colors, not the statistics.

  • na.value = "grey85" gives missing values a separate gray color. Missing does not mean zero.

Labels and Categorical Fill

asia_plot <- ggplot(East_Asia_map, aes(long, lat)) +
  geom_polygon(aes(group = group,
                   fill = region)) +
  geom_text(data = region_data,
            aes(label = region, colour = label_color),
            size = 5) +
  scale_colour_identity() +
  scale_fill_viridis_d() +
  coord_quickmap() +
  theme_void() +
  theme(legend.position = "none")

asia_plot

A Choropleth Map: Data

A choropleth represents a variable using the fill color of each region.

drinks <- read_csv("drinks.csv")

# Lesson helper: country-name correspondences.
country_names <- read_csv(
  "country_name_lookup.csv"
)


The lookup connects alternative country names. Separate island regions can share one country record.

A first look at the data

Country Litres / person
Afghanistan 0.0
Albania 4.9
Algeria 0.7
Andorra 12.4
Angola 5.9
Antigua & Barbuda 4.9


Historical teaching data: 2010.

FiveThirtyEight / WHO GISAH.

Why a Country-Name Lookup File?

The same country, different names

left_join() matches text exactly. These pairs refer to the same country but do not match as written.

In drinks.csv In the map boundaries
Russian Federation Russia
United Kingdom UK
Cote d’Ivoire Ivory Coast

Without a correspondence, the map would show missing alcohol statistics for these regions.

A transparent lesson helper

country_name_lookup.csv was created for this lesson with Codex, by comparing names in the two sources. It is a manually prepared correspondence table, not an official downloaded dataset.

  • region is the name used by the boundary database.
  • country is the name used by drinks.csv.
  • Separate island regions can share one country record.

Keeping the small lookup separate makes the changes visible and reusable while preserving the original data. Students can open the CSV and inspect every pairing.

Country Names and the Join

map_keys <- map %>%
  distinct(region) %>%
  left_join(country_names, by = "region") %>%
  mutate(country = coalesce(country, region))

drinks_map <- map %>%
  left_join(map_keys, by = "region") %>%
  left_join(drinks, by = "country")

# Checking the Country Match
unmatched_countries <- drinks %>%
  anti_join(map_keys, by = "country") %>%
  select(country)

unmatched_countries 

Checking the match

No matching boundary
Tuvalu

Start with the boundaries to preserve polygon order and keep regions without statistics.


  • coalesce(country, region) uses the original region name when the lookup has no alternative.

  • anti_join() identifies data rows without a matching key. An absent boundary needs another map source.


Tuvalu has no region in this database. Missing statistics appear in gray.

A Choropleth Map

world_drinks <- ggplot(
  drinks_map, aes(long, lat, group = group)) +
  geom_polygon(
    aes(fill = total_litres_of_pure_alcohol),
    colour = "white", linewidth = 0.1
  ) +
  scale_fill_viridis_c(na.value = "grey85") +
  coord_quickmap() +
  labs(fill = "Pure alcohol (litres/person)",
       caption = "WHO GISAH, 2010; missing data in gray") +
  theme_void() +
  theme(legend.position = "bottom")

world_drinks

A U.S. State-Level Map: Labels

US_map <- map_data("state")

state_lookup <- tibble(
  region = tolower(state.name),
  region_abb = state.abb
)

state_data <- US_map %>%
  group_by(region) %>%
  summarise(long = mean(long),
            lat = mean(lat)) %>%
  inner_join(state_lookup, by = "region")

Names connect the labels

Region key Label
alabama AL
alaska AK
arizona AZ
arkansas AR
california CA
colorado CO

Join by state name rather than relying on row order.

This database shows the contiguous United States. Overlapping labels are omitted on the next map.

A U.S. State-Level Map

p <- ggplot(US_map, aes(long, lat)) +
  geom_polygon(aes(group = group,
                   fill = region),
               colour = "white",
               linewidth = 0.2) +
  geom_text(data = state_data,
            aes(label = region_abb),
            size = 3.5, check_overlap = TRUE) +
  coord_quickmap() +
  theme_void() +
  theme(legend.position = "none")

p

check_overlap = TRUE skips labels that would overlap an earlier label. It does not move the label positions or remove states from the map.

Plotly: Conversion and Figure Size

Convert a finished ggplot

ggplotly(p, height = 540) %>%
  config(responsive = TRUE)


  • p is an existing ggplot object. ggplotly() converts it to an HTML widget with pointer interaction.

  • config() sets the widget’s interaction and display options.

Size and browser behavior

Argument Effect
height = 540 Figure height in pixels
width = 700 Optional fixed width in pixels
responsive = TRUE Allow resizing with the browser


We leave width unspecified so the map can fit its slide column. The slide also refits widgets when a page becomes visible.

Try: increase height to 620. The map gains vertical space; the data do not change.

A Dynamic Map Using plotly - 1

ggplotly() adds interaction to a ggplot object. Move the pointer over the map to inspect the available information.

library(plotly)

ggplotly(p, height = 540) %>%
  config(responsive = TRUE)

Plotly: Custom Hover Text

Define the text in a layer

aes(
  group = group,
  fill = region,
  text = str_to_title(region)
)


  • text stores the message for each region. Here, str_to_title() changes "ohio" to "Ohio".

  • A static ggplot may warn that text is an unknown aesthetic. Plotly reads it during conversion.

Select it during conversion

ggplotly(
  g, tooltip = "text", height = 540
)


  • tooltip = "text" displays the custom text instead of the default collection of mapped values.


For statistics, construct a message such as:

paste0(full, ": ", Murder,
       " arrests per 100,000 (1973)")
  • paste0() combines text and values without adding spaces automatically.

A Dynamic Map Using plotly - 2

A custom tooltip can show the state name over the whole polygon.

g <- ggplot(US_map, aes(long, lat)) +
  geom_polygon(
    aes(group = group, fill = region,
        text = str_to_title(region)),
    colour = "white", linewidth = 0.2
  ) +
  coord_quickmap() +
  theme_void() +
  theme(legend.position = "none")

ggplotly(g, tooltip = "text", height = 540) %>%
  config(responsive = TRUE)

A Dynamic Map Using plotly - 3: Data

library(usmap)
library(sf)

US_sf <- us_map("state") %>%
  filter(full %in% state.name)

crimes <- tibble(
  region = rownames(USArrests), USArrests
)
crimes_map <- US_sf %>%
  left_join(crimes, by = c("full" = "region"))

Geography and statistics

State Murder arrests / 100,000
Alabama 13.2
Alaska 10.0
Arizona 8.1
Arkansas 8.8
California 9.0

us_map("state") selects state boundaries. usmap includes Alaska and Hawaii as insets.

An sf object stores the boundary coordinates together in a geometry column. geom_sf() reads that column, so it needs no explicit long, lat, or group.

These are 1973 arrest rates.

A Dynamic Map Using plotly - 3

g1 <- ggplot(crimes_map) +
  geom_sf(
    aes(fill = Murder,
        text = paste0(full, ": ", Murder,
                      " arrests per 100,000 (1973)")),
    colour = "white", linewidth = 0.2
  ) +
  scale_fill_viridis_c(option = "B") +
  labs(fill = "Arrests per 100,000",
       caption = "USArrests: 1973 arrest data") +
  theme_void()

ggplotly(g1, tooltip = "text", height = 540) %>%
  config(responsive = TRUE)

Plotly: Hover Labels and Controls

Styling the hover box

hover_style <- list(
  bgcolor = "#232F34",
  bordercolor = "transparent",
  font = list(family = "Arial",
              size = 15, color = "white")
)

style(widget, hoverlabel = hover_style)


  • widget represents a converted Plotly figure. style() changes properties of its plotted traces, including hover labels.

Appearance and interaction

Argument Meaning
bgcolor Hover-box background color
bordercolor Hover-box outline color
font Font family, size in pixels, and text color
hoverlabel The settings list passed to style()


Later, config(displayModeBar = FALSE) hides the Plotly toolbar. Hover information still works.

Try: change bgcolor to "white" and the font color to "black".

A Dynamic Map Using plotly - 4

The hover label can use its own font and background. The map legend continues to explain the fill colors.

hover_style <- list(
  bgcolor = "#232F34",
  bordercolor = "transparent",
  font = list(family = "Arial",
              size = 15, color = "white")
)

ggplotly(g1, tooltip = "text", height = 540) %>%
  style(hoverlabel = hover_style) %>%
  config(responsive = TRUE)

A County-Level Map - 1

library(readxl)

poverty <- read_excel(
  "Poverty2023.xlsx",
  sheet = "Poverty Data 2023", skip = 4
)


ohio_data <- poverty %>%
  filter(Stabr == "OH", FIPS_Code != "39000") %>%
  transmute(
    fips = FIPS_Code,
    county_name = Area_Name,
    poverty_count = POVALL_2023,
    poverty_pct = PCTPOVALL_2023,
    median_income = MEDHHINC_2023
  )

From the workbook to 88 counties

2023 Census SAIPE estimates, compiled by USDA ERS.

Skip the first four documentation rows. Remove 39000, the statewide aggregate.

Field Meaning
fips County identifier, as text
poverty_count People in poverty
poverty_pct Percent in poverty
median_income Median household income

13.2 means 13.2%, not 0.132. The second worksheet defines the original fields.

Ohio County Boundaries

ohio_sf <- us_map("county", include = "OH") %>%
  st_transform(4326) %>%
  left_join(ohio_data, by = "fips")

stopifnot(
  nrow(ohio_sf) == 88,
  !anyDuplicated(ohio_data$fips),
  !anyNA(ohio_sf$poverty_pct)
)


  • Join key: FIPS
    Connect the datasets using county codes stored as text.

  • Select counties: us_map()
    Use include = "OH" to select Ohio counties.

  • Convert coordinates: st_transform()
    Use 4326 for WGS84 longitude and latitude.

  • Check the data: stopifnot()
    Check for 88 counties, unique keys, and no missing rates.

Joined county boundaries

Spatial Functions for Label Locations

A reusable coordinate recipe

ohio_sf %>%
  st_transform(32123) %>%
  st_point_on_surface() %>%
  st_transform(4326)


32123 identifies NAD83 / Ohio North, a projected coordinate system in metres. 4326 identifies WGS84 longitude and latitude in degrees.

Use the projected system to calculate interior points, then convert them back for this map. The code numbers identify coordinate systems; students can reuse them.

What the sf functions return

Function Result
st_point_on_surface() One interior point per county feature
st_coordinates() A matrix of point X and Y coordinates
st_drop_geometry() An ordinary table without the geometry column
st_crs(4326) The coordinate-system definition used by coord_sf()

An interior point is a practical label anchor. It is not necessarily the centroid or the county seat.

County Label Locations

ohio_labels <- ohio_sf %>%
  st_transform(32123) %>%
  st_point_on_surface() %>%
  st_transform(4326)

label_xy <- st_coordinates(ohio_labels)
ohio_labels <- ohio_labels %>%
  st_drop_geometry() %>%
  mutate(
    long = label_xy[, 1], lat = label_xy[, 2],
    label = str_remove(county, " County$"),
    long = long + case_when(
      label == "Richland" ~ -0.07,
      label == "Ashland" ~ 0.06,
      TRUE ~ 0)
  )

Interior label points

label_xy[, 1] supplies X (longitude), and label_xy[, 2] supplies Y (latitude). The last case_when() nudges two labels horizontally to reduce overlap.

A County-Level Map - 2

g2 <- ggplot(ohio_sf) +
  geom_sf(aes(fill = poverty_pct),
          colour = "white", linewidth = 0.15) +
  geom_text(data = ohio_labels,
            aes(long, lat, label = label),
            colour = "#102A43", size = 3) +
  coord_sf(crs = st_crs(4326), expand = FALSE) +
  scale_fill_gradient(low = "#EDF4FA", 
                      high = "#6B9EC5") +
  labs(fill = "Poverty (%)",
       caption = "2023 Census SAIPE; USDA ERS") +
  theme_void(base_size = 13)

g2

  • coord_sf(crs = st_crs(4326)) chooses the displayed coordinate system.
  • expand = FALSE removes automatic padding around the coordinate range.
  • scale_fill_gradient() uses light blue for the lowest rates and darker blue for the highest. low and high set the endpoint colors.

A County-Level Map: Interaction

The tooltip reports each county’s published estimate. aes(text = ...) adds a custom message to the existing map; tooltip = "text" selects that message.

g2_hover <- g2 +
  aes(text = paste0(county, ": ", poverty_pct,
                    "% in poverty (2023)"))

ggplotly(g2_hover, tooltip = "text",
         height = 650) %>%
  config(responsive = TRUE,
         displayModeBar = FALSE)

Bubble Map: People in Poverty

The same counties, a different measure

Map Visual encoding
Filled map Color shows poverty percentage
Bubble map Circle area shows people in poverty
bubble_data <- ohio_labels %>%
  arrange(desc(poverty_count))

bubble_data %>%
  select(label, poverty_count, poverty_pct) %>%
  slice_head(n = 5)


Draw large circles first. Transparency helps show overlap.

Largest poverty counts

County People %
Franklin 195,004 15.1
Cuyahoga 193,220 16.0
Hamilton 109,421 13.6
Montgomery 79,116 15.2
Lucas 75,810 18.2

A large count can occur alongside a moderate rate.

Each point represents its county, not the locations of individual households.

Bubble Area and Point Appearance

Area represents the count

aes(size = poverty_count)

scale_size_area(
  max_size = 18,
  breaks = c(10000, 50000, 100000),
  labels = scales::label_comma()
)


scale_size_area() makes circle area proportional to the value. Twice as many people gives twice the area, not twice the diameter. A value of zero has zero area.

The arguments used next

Argument Meaning
max_size Largest displayed circle size
breaks Reference counts shown in the size legend
labels How legend values are formatted
shape = 21 A circle with separate fill and outline
alpha = 0.65 Partial transparency, on a 0–1 scale
stroke Point-outline thickness

scales::label_comma() formats 10000 as 10,000. Legend breaks do not filter out other counties.

Bubble Map

bubble_map <- ggplot(ohio_sf) +
  geom_sf(fill = "grey96", colour = "grey75",
          linewidth = 0.2) +
  geom_point(
    data = bubble_data,
    aes(long, lat, size = poverty_count),
    shape = 21, fill = "#177E89", 
    colour = "#144552",
    alpha = 0.65, stroke = 0.3
  ) +
  scale_size_area(
    max_size = 18,
    breaks = c(10000, 50000, 100000),
    labels = scales::label_comma()
  ) +
  coord_sf(crs = st_crs(4326), expand = FALSE) +
  labs(size = "People in poverty",
       caption = "2023 Census SAIPE; USDA ERS") +
  theme_void(base_size = 13)

bubble_map

Bubble Map: Interaction

bubble_hover <- bubble_map +
  aes(text = paste0(county, ": ",
    scales::comma(poverty_count), " people; ",
    poverty_pct, "% (2023)"))

ggplotly(bubble_hover, tooltip = "text",
         height = 650) %>%
  config(responsive = TRUE,
         displayModeBar = FALSE)

scales::comma() formats the count inside each hover message. The message includes both people and percent, making the distinction visible while students explore.

Bubble Map: Comparison

Percentage of people

Number of people

Discuss: Do the same counties stand out? Explain why the two maps emphasize different places.

Practice: map median_income with circle area and revise the legend. What would a larger circle mean?

Data Sources

Poverty and income figures are estimates. The original workbook includes 90% confidence intervals.