Mapping with ggplot2

Robert Schlegel

Problem

  • Where do we start?
  • How do we show scale?
  • What if we need to inset a map?

Solution

  • tidyverse contains default mapping support
  • ggsn provides code for scale bars
  • Maps are the same as basic plots, so can be combined as grob’s

Setup

library(tidyverse) # Contains most of what we need

library(ggpubr) # For combining figures

library(ggsn) # Contains code to make scale bars

library(palmerpenguins) # Data used in an example

Default map

earth_1 <- ggplot() +
  # The global shape file
  borders(fill = "grey70", colour = "black") +
  # Equal sizing for lon/lat 
  coord_equal()
earth_1

Cropping

green_1 <- ggplot() +
  borders(fill = "grey70", colour = "black") +
  # Force lon/lat extent
  coord_equal(xlim = c(-75, -10), ylim = c(58, 85)) 
green_1

Extract a region

  • This chunk contains some functions we will learn about on Day 4
map_data('world') %>% 
  select(region) %>% 
  distinct() %>% 
  arrange(region)
                                 region
1                           Afghanistan
2                               Albania
3                               Algeria
4                        American Samoa
5                               Andorra
6                                Angola
7                              Anguilla
8                            Antarctica
9                               Antigua
10                            Argentina
11                              Armenia
12                                Aruba
13                     Ascension Island
14                            Australia
15                              Austria
16                           Azerbaijan
17                               Azores
18                              Bahamas
19                              Bahrain
20                           Bangladesh
21                             Barbados
22                              Barbuda
23                              Belarus
24                              Belgium
25                               Belize
26                                Benin
27                              Bermuda
28                               Bhutan
29                              Bolivia
30                              Bonaire
31               Bosnia and Herzegovina
32                             Botswana
33                               Brazil
34                               Brunei
35                             Bulgaria
36                         Burkina Faso
37                              Burundi
38                             Cambodia
39                             Cameroon
40                               Canada
41                       Canary Islands
42                           Cape Verde
43                       Cayman Islands
44             Central African Republic
45                                 Chad
46                   Chagos Archipelago
47                                Chile
48                                China
49                     Christmas Island
50                        Cocos Islands
51                             Colombia
52                              Comoros
53                         Cook Islands
54                           Costa Rica
55                              Croatia
56                                 Cuba
57                              Curacao
58                               Cyprus
59                       Czech Republic
60     Democratic Republic of the Congo
61                              Denmark
62                             Djibouti
63                             Dominica
64                   Dominican Republic
65                              Ecuador
66                                Egypt
67                          El Salvador
68                    Equatorial Guinea
69                              Eritrea
70                              Estonia
71                             Ethiopia
72                     Falkland Islands
73                        Faroe Islands
74                                 Fiji
75                              Finland
76                               France
77                        French Guiana
78                     French Polynesia
79  French Southern and Antarctic Lands
80                                Gabon
81                               Gambia
82                              Georgia
83                              Germany
84                                Ghana
85                               Greece
86                            Greenland
87                              Grenada
88                           Grenadines
89                           Guadeloupe
90                                 Guam
91                            Guatemala
92                             Guernsey
93                               Guinea
94                        Guinea-Bissau
95                               Guyana
96                                Haiti
97                         Heard Island
98                             Honduras
99                              Hungary
100                             Iceland
101                               India
102                           Indonesia
103                                Iran
104                                Iraq
105                             Ireland
106                         Isle of Man
107                              Israel
108                               Italy
109                         Ivory Coast
110                             Jamaica
111                               Japan
112                              Jersey
113                              Jordan
114                          Kazakhstan
115                               Kenya
116                            Kiribati
117                              Kosovo
118                              Kuwait
119                          Kyrgyzstan
120                                Laos
121                              Latvia
122                             Lebanon
123                             Lesotho
124                             Liberia
125                               Libya
126                       Liechtenstein
127                           Lithuania
128                          Luxembourg
129                          Madagascar
130                     Madeira Islands
131                              Malawi
132                            Malaysia
133                            Maldives
134                                Mali
135                               Malta
136                    Marshall Islands
137                          Martinique
138                          Mauritania
139                           Mauritius
140                             Mayotte
141                              Mexico
142                          Micronesia
143                             Moldova
144                              Monaco
145                            Mongolia
146                          Montenegro
147                          Montserrat
148                             Morocco
149                          Mozambique
150                             Myanmar
151                             Namibia
152                               Nauru
153                               Nepal
154                         Netherlands
155                               Nevis
156                       New Caledonia
157                         New Zealand
158                           Nicaragua
159                               Niger
160                             Nigeria
161                                Niue
162                      Norfolk Island
163                         North Korea
164                     North Macedonia
165            Northern Mariana Islands
166                              Norway
167                                Oman
168                            Pakistan
169                               Palau
170                           Palestine
171                              Panama
172                    Papua New Guinea
173                            Paraguay
174                                Peru
175                         Philippines
176                    Pitcairn Islands
177                              Poland
178                            Portugal
179                         Puerto Rico
180                               Qatar
181                   Republic of Congo
182                             Reunion
183                             Romania
184                              Russia
185                              Rwanda
186                                Saba
187                    Saint Barthelemy
188                        Saint Helena
189                         Saint Kitts
190                         Saint Lucia
191                        Saint Martin
192           Saint Pierre and Miquelon
193                       Saint Vincent
194                               Samoa
195                          San Marino
196               Sao Tome and Principe
197                        Saudi Arabia
198                             Senegal
199                              Serbia
200                          Seychelles
201                     Siachen Glacier
202                        Sierra Leone
203                           Singapore
204                      Sint Eustatius
205                        Sint Maarten
206                            Slovakia
207                            Slovenia
208                     Solomon Islands
209                             Somalia
210                        South Africa
211                       South Georgia
212                         South Korea
213              South Sandwich Islands
214                         South Sudan
215                               Spain
216                           Sri Lanka
217                               Sudan
218                            Suriname
219                           Swaziland
220                              Sweden
221                         Switzerland
222                               Syria
223                              Taiwan
224                          Tajikistan
225                            Tanzania
226                            Thailand
227                         Timor-Leste
228                              Tobago
229                                Togo
230                               Tonga
231                            Trinidad
232                             Tunisia
233                              Turkey
234                        Turkmenistan
235            Turks and Caicos Islands
236                              Uganda
237                                  UK
238                             Ukraine
239                United Arab Emirates
240                             Uruguay
241                                 USA
242                          Uzbekistan
243                             Vanuatu
244                             Vatican
245                           Venezuela
246                             Vietnam
247                      Virgin Islands
248                   Wallis and Futuna
249                      Western Sahara
250                               Yemen
251                              Zambia
252                            Zimbabwe

Extract a region

map_data_green <- map_data('world') %>% 
  filter(region == "Greenland") # Why '==' and not '='?
head(map_data_green)
       long      lat group order    region subregion
1 -46.26670 60.78139   648 43088 Greenland         1
2 -46.38154 60.66031   648 43089 Greenland         1
3 -46.49634 60.68667   648 43090 Greenland         1
4 -46.55312 60.74077   648 43091 Greenland         1
5 -46.66621 60.76592   648 43092 Greenland         1
6 -46.78809 60.75840   648 43093 Greenland         1

A new concept?

  • A basic map is the same as a scatterplot with an x and y axis
  • Compare a dot plot of penguin weight data against a dot plot of the coastline of Greenland

Penguin dots:

ggplot(data = penguins, 
       aes(x = body_mass_g, y = bill_length_mm)) +
  geom_point()

Greenland coast dots:

ggplot(data = map_data_green, 
       aes(x = long, y = lat)) +
  geom_point()

Polygons

  • Dots are not the ideal method for creating maps
  • For that we want to use polygons
  • Be careful with these, they can be a bit tricky

Polygons

green_2 <- ggplot(data = map_data_green, aes(x = long, y = lat)) +
  # What is this doing?
  geom_polygon(aes(group = group), 
               # Note these are outside of aes() 
               fill = "chartreuse4", colour = "black")
green_2

Specific labels

  • A map is almost always going to need some labels and other visual cues
  • The following code chunk shows how we can add one label at a time
  • This is useful if each label needs to be different from the others
  • We also see that some text labels have \n in them
  • This is how we tell R to return down a line

Specific labels

green_3 <- green_2 +
  # Add Greenland text
  annotate("text", label = "Greenland", 
           x = -40, y = 75.0, size = 7.0, fontface = "bold.italic") +
  # Add North Atlantic Ocean text
  annotate("text", label = "North\nAtlantic\nOcean", 
           x = -20, y = 64.0, size = 5.0,  angle = 330, colour = "navy") +
  # Add Baffin Bay label
  annotate("label", label = "Baffin\nBay", 
           x = -62, y = 70, size = 5.0, fill = "springgreen") +
  # Add black line under Greenland text
  annotate("segment", 
           x = -50, xend = -30, y = 73, yend = 73)
green_3

Scale bars

  • There is no default scale bar function in the tidyverse
  • ggsn is devoted to adding scale bars and North arrows for ggplot2
  • There are heaps of options so we’ll just focus on one of them for now
  • We may see the list of available North arrow shapes by running northSymbols().

Scale bars

green_4 <- green_3 +
  # Set location of bar,
  scalebar(data = map_data_green, location = "bottomleft", 
           # Size of scale bar
           dist = 500, dist_unit = "km", transform = TRUE,
           # Set particulars
           st.size = 4, height = 0.03, st.dist = 0.04) 
green_4

Insetting

  • ggplot2 stores data in the object type grob
  • We convert other objects to inset them via ggplotGrob
  • The insetting is performed with annotation_custom()
  • This is a good way to add logos etc. to a map/figure
  • It’s even possible to add GIFs (see Bonus content)

Insetting

  • Create a map to use as an inset
earth_2 <- earth_1 + 
  geom_rect(aes(xmin = -75, xmax = -10, ymin = 58, ymax = 85),
            fill = NA, colour = "red") +
  # What does this do?
  theme_void()
earth_2

Insetting

  • Inset it over the greenland map
green_5 <- green_4 +
  # Convert the earth plot to a grob
  annotation_custom(grob = ggplotGrob(earth_2), 
                    xmin = -30, xmax = -10,
                    ymin = 76, ymax = 84)
green_5

Rounding it out

  • Add units to the lon/lat coordinates
green_final <- green_5 +
  scale_x_continuous(breaks = seq(-60, -20, 20),
                     labels = c("60°W", "40°W", "20°w"),
                     position = "bottom") +
  scale_y_continuous(breaks = seq(60, 80, 10),
                     labels = c("60°N", "70°N", "80°N"),
                     position = "right") +
  labs(x = "", y = "") +
  theme_bw()
green_final

Rounding it out

  • And lastly we save the fruits of our labours
ggsave(plot = sa_final, filename = "figures/green_final.pdf", 
       height = 6, width = 8)