Basic world map with ggplot
Last time I installed R was because I wanted to play with
ggplot for for the #30DayMapChallenge in 2021.
ggplot is one of the best R packages for DataViz.
Here’s how to make a basic world map with
ggplot. A explanation of what’s going on (to the best of my newbie knowledge) comes after.
library(ggplot2) library(sf) library(rnaturalearth) library(rnaturalearthdata) world <- ne_countries(scale = "medium", returnclass = "sf") ggplot(data = world) + geom_sf(color = "black", fill = "white") + coord_sf(crs = "+proj=laea +ellps=GRS80 +lat_0=36 +lon_0=10" ) + # graticule and background color theme(panel.grid.major = element_line(color = "white", linetype = "dashed", size = 0.5), panel.background = element_rect(fill = "black"))
First things first.
library(ggplot2) library(sf) library(rnaturalearth) library(rnaturalearthdata)
Pretty obvious, load the necessary packages to create the map:
sfis a package for working with spatial data
rnaturalearthdataare datasets from the natural earth project.
world <- ne_countries(scale = "medium", returnclass = "sf")
This line loads the world map data using the
ne_countries function from the
rnaturalearth. The scale argument specifies the level of detail, we set it to “medium”. The returnclass argument specifies the format of the output, we want
sf. We store the result in a variable called world.
ggplot(data = world)
This line sets up the basic plot framework in ggplot. The data argument specifies the dataset to use for the plot
geom_sf(color = "black", fill = "white")
This line adds a geom_sf layer to the ggplot object. geom_sf is a special type of ggplot geometry used for plotting spatial data in the sf format. The color argument specifies the color of the polygon borders, and the fill argument specifies the fill color of the polygons.
coord_sf(crs = "+proj=laea +ellps=GRS80 +lat_0=36 +lon_0=10" )
All the acronyms, here we go. We set the coordinate reference system (CRS) for the plot. The projection is set to
laea which obviously means Lambert azimuthal equal-area (what else?) and we center the map on 36 in latitude and 10 in longitude. Here are some tips if, like me, you’re never sure which is which.
theme(panel.grid.major = element_line(color = "white", linetype = "dashed", size = 0.5), panel.background = element_rect(fill = "black"))
Almost done. The theme function customises the appearance of the plot. The
panel.grid.major argument specifies the appearance of the major grid lines, aka graticules, which are set to white, dashed, and 0.5 in size. The
panel.background argument specifies the background color of the plot, which we set to black.
I hope that was good enough to help you get started! I gave up after this and went back to with D3.js. At least it’s a complicated mess that I am familiar with.