Site icon R-bloggers

How to plot basic maps with ggmap

[This article was first published on r-bloggers – SHARP SIGHT LABS, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

When you’re learning data science – and specifically data science in R using the Tidyverse – it is very helpful to learn individual techniques in a highly modular way.

This is because large projects, when you really break them down, are just combinations of small techniques. If you master all of those little tools and techniques on a small scale then you can combine them together later to create more complex charts, graphs, and analyses.

At a very basic level, this means that you should master fundamental tools like < inline_code>geom_bar(), < inline_code>geom_line(), and < inline_code>geom_point(). After you master those very simple tools, you can learn additional tools that can be combined with the basics.

A good example of this is < inline_code>ggmap. The < inline_code>ggmap package allows you to download and plot basic maps from Google maps (and a few other sources). These maps can then be used as layers within the < inline_code>ggplot2 plotting system. Essentially, you can plot maps from < inline_code>ggmap, and then use < inline_code>ggplot2 to plot points and other geoms on top of the map. Using < inline_code>ggplot+< inline_code>ggmap this way is extremely useful for quick-and-dirty geospatial visualization.

With that in mind, I want to quickly show you how to use < inline_code>ggmap to download and plot maps.

First, let’s just load the packages that we will use. Here, we’re going to load < inline_code>ggmap and < inline_code>tidyverse. < inline_code>ggmap will allow us to access Google Maps, but we’ll also use < inline_code>tidyverse for some additional plotting and other functionality (like pipes).

#==============
# LOAD PACKAGES
#==============

library(ggmap)
library(tidyverse)

Now that our packages are downloaded, let’s just get a simple map. Here, we’ll retrieve a basic map of Tokyo from Google Maps.

#=================
# GET MAP OF Tokyo
#=================

map.tokyo <- get_map("Tokyo")
ggmap(map.tokyo)



Notice that we’ve used two functions.

First we used < inline_code>get_map() to retrieve the map from Google Maps. To do this, we just specified the name of the location (more on that later).

Next, we used < inline_code>ggmap() to plot the map.

In doing this, I saved the map first with the name < inline_code>map.tokyo. It can be useful sometimes to save a map like this with a name, but sometimes you don’t need the name. In fact, if you don’t need to save the map, then it can be useful to avoid doing so; finding names for little objects like this can become tiresome.

Having said that, we can actually retrieve and plot the map in a single line of code, without saving the map object.

To do this, we will use the tidyverse “pipe” operator, < inline_code>%>%. (Note: this is one of the reasons that we loaded the < inline_code>tidyverse package.)

#=============================================
# USE THE PIPE OPERATOR
# - Here, we're basically doing the same thing
#   but we will do it in one line of code
#=============================================

get_map("Tokyo") %>% ggmap()



Essentially, what we’ve done here is retrieved the map using < inline_code>get_map(), but then immediately “piped” it into < inline_code>ggmap(). Again, this can be useful because the code is cleaner … we don’t need an intermediate name.

Now let’s plot a different map. Here we will plot a map of Japan.

#==========================================
# GET MAP OF JAPAN
# - this doens't work well without zooming
#==========================================

get_map("Japan") %>% ggmap()



This code works in a similar way: we just provide the location name to < inline_code>get_map(), and then pipe it into < inline_code>ggmap().

Having said that, this plot is not very good, because it’s not really zoomed properly.

To fix this, we will use the < inline_code>zoom parameter of < inline_code>get_map() to zoom out.

#===========================================
# GET MAP OF JAPAN, ZOOMED
# - here, we are manually setting the zoom
#   to get a better map
# - to find the best setting for 'zoom', 
#   you'll need to use some trial-and-error
#===========================================

get_map("Japan", zoom = 5) %>% ggmap()



This is much better.

Keep in mind that to get the right setting for zoom, you’ll typically need to use a bit of trial-and-error.

Next, we’ll get a map of a more specific location. Here we will get a map of Shinjuku, an area of Tokyo.

Notice that as we do this, we are again just specifying the location and zooming in properly with the < inline_code>zoom parameter.

#==============================
# GET MAP OF SPECIFIC LOCATION
#==============================

# note: not zoomed enough
get_map("Shinjuku") %>% ggmap()


# this is properly zoomed
get_map("Shinjuku", zoom = 16) %>% ggmap()



So there you have it. That’s the quick introduction to < inline_code>ggmap.

To be clear, there’s actually quite a bit more functionality for < inline_code>get_map(), but in the interest of simplicity, you should master these techniques first. Later, once you have mastered these simple < inline_code>ggmap tools, you can start combining maps from < inline_code>ggmap() with tools from < inline_code>ggplot2:

# CREATE DATA FRAME
df.tokyo_locations <- tibble(location = c("Ueno, Tokyo, Japan"
                                          ,"Shibuya, Tokyo, Japan"
                                          ,"Shinjuku, Tokyo, Japan"))


# GEOCODE
geo.tokyo_locations <- geocode(df.tokyo_locations$location)


# COMBINE DATA
df.tokyo_locations <- cbind(df.tokyo_locations, geo.tokyo_locations)


# USE WITH GGPLOT
get_map("Tokyo", zoom = 12) %>% ggmap() +
  geom_point(data = df.tokyo_locations, aes(x = lon, y = lat), color = 'red', size = 3)



By the way, this is exactly why I recommend learning and mastering simple tools like < inline_code>geom_point() first … once you have mastered simple tools, you can start combining them together like building-blocks to create more advanced visualizations and analyses.

Sign up to master R

Want to master R?

Here at Sharp Sight, we teach data science in R.

And we not only show you the techniques, we will show you how to practice those techniques so that you master them.

So if you want to master data science and become “fluent” in R, sign up for our email newsletter.

When you sign up, you’ll get:
– ggplot2 data visualization tutorials
– tutorials on how to practice ggplot2 syntax (so you can write code “with your eyes closed”)
– practice tips to help you master and memorize syntax

You’ll also get access to our “Data Science Crash Course” for free.

SIGN UP NOW

The post How to plot basic maps with ggmap appeared first on SHARP SIGHT LABS.

To leave a comment for the author, please follow the link and comment on their blog: r-bloggers – SHARP SIGHT LABS.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.