library(here)
Mapping in R
Create a map of Europe in ggplot2.
Intro
How to create a map in ggplot and add attributes.
Getting ready
You can download shapefiles from: https://www.naturalearthdata.com/downloads/
Call the package here to work in your directory.
Call the package sf to read the shapefiles into R
library(sf)
Read your shapefile
Use your directory name, and give the name of your shapefile
<-st_read(paste0(Directory,MyShapefileName)) Europe
Create a basic map
Load ggplot2
library(ggplot2)
Plot your shapefile
ggplot()+
geom_sf(data = Europe)
Add colors
I copy the hex colors from coolors
ggplot()+
geom_sf(data = Europe,
colour = "#edf2f4",
fill = "#2b2d42",
size=0.5)
Change background color
You can eliminate the grids and the change the background color in ggplot
ggplot()+
geom_sf(data = Europe,
colour = "#edf2f4",
fill = "#2b2d42",
size=0.5)+
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(fill = '#edf2f4'),
legend.background = element_rect(fill = '#edf2f4'))
Add limits
Reduce to focus in your area of interest
ggplot()+
geom_sf(data = Europe,
colour = "#edf2f4",
fill = "#2b2d42",
size=0.5)+
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(fill = '#edf2f4'),
legend.background = element_rect(fill = '#edf2f4'))+
coord_sf(xlim = c(9, 31),ylim = c(53, 65))
Add scale
Load the package ggspatial to add a scale and an north arrow
library(ggspatial)
br is from bottom right
bar_cols is for column colors
text_col is for the color of the text
ggplot()+
geom_sf(data = Europe,
colour = "#edf2f4",
fill = "#2b2d42",
size=0.5)+
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(fill = '#edf2f4'),
legend.background = element_rect(fill = '#edf2f4'))+
coord_sf(xlim = c(9, 31),ylim = c(53, 65))+
scale_x_continuous(labels = function(x) paste0(x, '\u00B0', "W")) +
scale_y_continuous(labels = function(x) paste0(x, '\u00B0', "N")) +
annotation_scale(location = "br",bar_cols = c("#ef233c", "#d90429"),text_col = '#ef233c')
Add arrow
tl is for top left
which_north preferably true (see why here)
north_arrow_fancy_orienteering (see other styles here)
ggplot()+
geom_sf(data = Europe,
colour = "#edf2f4",
fill = "#2b2d42",
size=0.5)+
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_rect(fill = '#edf2f4'),
legend.background = element_rect(fill = '#edf2f4'))+
coord_sf(xlim = c(9, 31),ylim = c(53, 65))+
scale_x_continuous(labels = function(x) paste0(x, '\u00B0', "W")) +
scale_y_continuous(labels = function(x) paste0(x, '\u00B0', "N")) +
annotation_scale(location = "br",bar_cols = c("#ef233c", "#d90429"),text_col = '#ef233c')+
annotation_north_arrow(location = "tl", style = north_arrow_minimal(text_col = '#ffd60a',line_col = '#ffd60a',fill = '#ffd60a'))
Thats it for now!