This post introduces the tmap package in R, explaining how to create thematic maps. It provides simple, reproducible code examples and explains the main concepts behind tmap.
The tmap package is a powerful tool
for creating thematic maps in R. It provides an intuitive and flexible
way to visualize spatial data, similar to how ggplot2
works
for general data visualization.
First, let’s install and load the tmap package. We’ll use the built-in
World
dataset for our examples.
The main concept in tmap is building
maps using layers. You start with tm_shape()
to define the
data, then add layers with various tm_*()
functions.
Let’s create a simple world map:
This creates a basic world map where each country is a polygon.
We can add data to our map by specifying a variable in
tm_polygons()
:
Here, we’re coloring countries based on their population estimates.
tmap offers many ways to customize your map. Let’s add borders and adjust the color palette:
We can add multiple layers to our map. Let’s add country names:
tmap can create both static and interactive maps. To switch to interactive mode:
tmap_mode("view")
my_tmap <- tm_shape(World) +
tm_polygons("pop_est", palette = "viridis", title = "Population")
tmap_save(my_tmap, filename = "HtmlWidget/416-introduction-to-tmap-interactive.html")
Remember to switch back to plot mode for static maps:
This introduction covered the basics of creating thematic maps with tmap. The package offers many more features for creating complex and informative maps. As you become more comfortable with these basics, you can explore more advanced features like faceting, small multiples, and custom projections.
👋 After crafting hundreds of R charts over 12 years, I've distilled my top 10 tips and tricks. Receive them via email! One insight per day for the next 10 days! 🔥