Bessie Lee
Bessie Lee

Reputation: 51

How to plot capital cities on an existing map in r

I made a map using ggplot (geom_map). My code looks pretty much like this :

gg <- ggplot()
gg <- gg + 
  geom_map(data=county, map=county,
           aes(long, lat, map_id=region),
           color="grey", fill=NA, size=0.15)

gg <- gg + 
  geom_map(data=state, map=state,
           aes(long, lat, map_id=region),
           color="black", fill=NA, size=0.5) +
  geom_label_repel(data = states, 
                   aes(long, lat, label = region), 
                   size = 2)

How do I add all capitals of the us to it, map.cities maybe?

Upvotes: 2

Views: 1634

Answers (1)

Anonymous coward
Anonymous coward

Reputation: 2091

You can use data from the maps library, called us.cities, which denotes capitals in it. You can use the geom_label in ggplot, but things are cleaner it the geom_label_repel from ggrepel, as you found out.

library(ggplot2)
library(maps)
library(ggrepel)

data(us.cities)
capitals <- subset(us.cities, capital == 2)
capitals_notAKHI <- capitals[!(capitals$country.etc %in% "AK" | capitals$country.etc %in% "HI"), ] #exclude Alaska and Hawaii
capitals_notAKHI$city <- sub(' [^ ]*$','',capitals_notAKHI$name) # split out city for the label

ggplot(capitals_notAKHI, aes(long, lat)) +
  borders("state") +
  geom_point() +
  coord_quickmap() +
  geom_label_repel(aes(label = city), size = 2)

Upvotes: 3

Related Questions