GGMap + GGPlot
We already know how to download part of an background map from Google Maps. Today we will plot our data on the downloaded map using the ggplot2 library. Let’s load the libraries we need:
library(rgdal) library(ggplot2) library(ggmap)
In our post, we’ll use railroad lines, which we’ve used many times before. Let’s load the layer:
kolej <- readOGR("D:/","railroad",stringsAsFactors = F)
To display the vector layer in ggplot, it is necessary to transform it into a data frame using the fortify function:
railroad_df <- fortify(railroad)
In the variable map we write the map we want to display:
map <- ggplot(railroad_df, aes(x=long,y= lat,group=group)) + geom_path(color = 'red',size=2) + ggtitle("Nasza mapa")
The individual map elements are:
ggplot() – initializes the object, we declare in it the input data (railroad_df) and coordinates and grouping variable aes()
geom_path() – a way to plot the data as lines according to their entry in the input table. Here we also define the color and size of the lines
ggtitle() – the name of the table
Display the result:
print(map)
Let’s now add the ggmap underlay to our railway lines. First we need to convert the vector layer to a geographic layout:
railroad_geog = spTransform(railroad,"+init=EPSG:4326")
We download a Google satellite map fragment for the vector layer:
sat_map <- get_map(location = railroad_geog@bbox, maptype = 'satellite')
We display the underlay:
ggmap(sat_map)
We transform the layer into a data frame:
railroad_df <- fortify(railroad_geog)
We store the map in a different way than before. The base is sat_map, on which we overlay geom_path()
map <- ggmap(sat_map) + geom_path(data = railroad_df, aes(x=long,y=lat,group=group),color = 'red',size=2)
Display the result:
print(map)
Ggplot is a very rich library for visualizing different types of data. It has something to offer for everyone. In this post we have shown how to use it simply to visualize shp levels on Google Maps, but we will certainly show you how to use other features of this library in the future.