Introduction

Getting started

#load packages
library(ggplot2)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(tidyr)
library(ggmap)

Getting started with data

We will use a made up dataset on polar bears

setwd("~/Documents/R/YorkU.DataViz.2017-06-19/data")
data <- read.csv("bears.csv")
head(data, 5)
##     bearID  Seal Beluga Walrus Year   Era  Region Bodycond   Lat    Long
## 1 BEAR0225 22.87  71.78   5.35 2000 Early Central    66.18 70.52 -122.98
## 2 BEAR0327 77.96  15.12   6.92 2000 Early Central    71.33 70.56 -122.47
## 3 BEAR0194 54.83  44.70   0.48 2000 Early Central    71.61 71.97 -125.37
## 4 BEAR0306 65.16  33.96   0.89 2000 Early Central    72.08 71.22 -118.12
## 5 BEAR0312 58.78  36.93   4.29 2000 Early Central    74.65 70.97 -121.75
##   Sex Ageclass
## 1   M    Adult
## 2   M    Adult
## 3   M    Adult
## 4   M Subadult
## 5   M    Adult

First, use ggplot2

world<-map_data("world", "Canada")
w <- fortify(world)

map <-ggplot(data, aes(Long,Lat)) + geom_polygon(data=w, colour="grey50", fill="grey50", aes(x=long, y=lat))+coord_map()+ ylim(67.5, 76.5) + xlim(-142,-100)

map + geom_point(data=data, aes(Long, Lat))

map + geom_point(data=data, aes(Long, Lat, shape=Sex, color=Sex),size=3)+  scale_color_manual(name="Sex", values=c("red","black")) + scale_shape_manual(name="Sex", values=c(15:16))

Change color/shape of variables: Discrete variable

#Basic
ggplot(data, aes(Long,Lat)) + geom_polygon(data=w, colour="grey50", fill="grey50", aes(x=long, y=lat))+coord_map()+ ylim(67.5, 76.5) + xlim(-142,-100)+ geom_point(data=data, aes(Long, Lat))

#Color by ageclass
ggplot(data, aes(Long,Lat, color=Ageclass)) + geom_polygon(data=w, colour="grey50", fill="grey50", aes(x=long, y=lat))+coord_map()+ ylim(67.5, 76.5) + xlim(-142,-100)+ geom_point(data=data, aes(Long, Lat))

#Manually select colors
ggplot(data, aes(Long,Lat, color=Ageclass)) + geom_polygon(data=w, colour="grey50", fill="grey50", aes(x=long, y=lat))+coord_map()+ ylim(67.5, 76.5) + xlim(-142,-100)+ geom_point(data=data, aes(Long, Lat))+  scale_color_manual(name="Ageclass", values=c("red","black","green"))

#Shape and color by ageclass 
ggplot(data, aes(Long,Lat, color=Ageclass)) + geom_polygon(data=w, colour="grey50", fill="grey50", aes(x=long, y=lat))+coord_map()+ ylim(67.5, 76.5) + xlim(-142,-100)+ geom_point(data=data, aes(Long, Lat, shape=Ageclass))+  scale_color_manual(name="Ageclass", values=c("red","black","green"))+ scale_shape_manual(name="Ageclass", values=c(15:17))

Change color/size of variables: Continuous variable

#Basic
ggplot(data, aes(Long,Lat)) + geom_polygon(data=w, colour="grey50", fill="grey50", aes(x=long, y=lat))+coord_map()+ ylim(67.5, 76.5) + xlim(-142,-100)+ geom_point(data=data, aes(Long, Lat))

#Color by Bodycond
ggplot(data, aes(Long,Lat, color=Bodycond)) + geom_polygon(data=w, colour="grey50", fill="grey50", aes(x=long, y=lat))+coord_map()+ ylim(67.5, 76.5) + xlim(-142,-100)+ geom_point(data=data, aes(Long, Lat))

#Color by Bodycond: manually set limits and colors
ggplot(data, aes(Long,Lat, color=Bodycond)) + geom_polygon(data=w, colour="grey50", fill="grey50", aes(x=long, y=lat))+coord_map()+ ylim(67.5, 76.5) + xlim(-142,-100)+ geom_point(data=data, aes(Long, Lat))+scale_color_gradient(limits=c(0,100), low = "green", high = "black", name = "A nice\nnew title")

#Color by Bodycond: break up gradient legend
ggplot(data, aes(Long,Lat, color=Bodycond)) + geom_polygon(data=w, colour="grey50", fill="grey50", aes(x=long, y=lat))+coord_map()+ ylim(67.5, 76.5) + xlim(-142,-100)+ geom_point(data=data, aes(Long, Lat))+scale_color_continuous(limits=c(40,100), low = "green", high = "black", name = "Body\ncondition",breaks = c(45, 95), labels = c("Skinny", "Fat"))

#Size by Bodycond: break up gradient legend
ggplot(data, aes(Long,Lat, color=Bodycond)) + geom_polygon(data=w, colour="grey50", fill="grey50", aes(x=long, y=lat))+coord_map()+ ylim(67.5, 76.5) + xlim(-142,-100)+ geom_point(data=data, aes(Long, Lat, size=Walrus))+scale_color_continuous(limits=c(40,100), low = "green", high = "black", name = "Body\ncondition",breaks = c(45, 95), labels = c("Skinny", "Fat"))

Add text

#Basic
ggplot(data, aes(Long,Lat)) + geom_polygon(data=w, colour="grey50", fill="grey50", aes(x=long, y=lat))+coord_map()+ ylim(67.5, 76.5) + xlim(-142,-100)+ geom_point(data=data, aes(Long, Lat))

#Add title
ggplot(data, aes(Long,Lat)) + geom_polygon(data=w, colour="grey50", fill="grey50", aes(x=long, y=lat))+coord_map()+ ylim(67.5, 76.5) + xlim(-142,-100)+ geom_point(data=data, aes(Long, Lat))+labs(title="New title")

#Add place names
ggplot(data, aes(Long,Lat)) + geom_polygon(data=w, colour="grey50", fill="grey50", aes(x=long, y=lat))+coord_map()+ ylim(67.5, 76.5) + xlim(-142,-100)+ geom_point(data=data, aes(Long, Lat))+labs(title="New title")+geom_text(aes(x=-127, y=68.5, label="N.W.T."), size=3, , color = "black")+geom_text(aes(x=-135, y=75, label="Beaufort\nSea"), size=4, color = "darkblue", fontface = "italic")+geom_text(aes(x=-110, y=71, label="Victoria\nIs."), size=3,color = "black")+geom_text(aes(x=-121, y=73, label="Banks\nIs."), size=3, , color = "black")+geom_text(aes(x=-111.5, y=75.75, label="Viscount\nMelville Is."), size=3, , color = "black") 

Ellipses

#Add ellipse to all points
map <-ggplot(data, aes(Long,Lat)) + geom_polygon(data=w, colour="grey50", fill="grey50", aes(x=long, y=lat))+coord_map()+ ylim(67.5, 76.5) + xlim(-142,-100)+geom_point(data=data, aes(Long, Lat, shape=Sex, color=Sex))+  scale_color_manual(name="Sex", values=c("red","blue")) + scale_shape_manual(name="Sex", values=c(15:16))

l<- map+geom_point(data=data, aes(x=Long, y=Lat, shape=Sex,color = Sex))+
stat_ellipse(geom="polygon", fill=NA,color="black",level = 0.50, type="t", size=2)+
stat_ellipse(geom="polygon", fill=NA, color="black",level = 0.75, type="t", linetype=2)
l

#Add ellipse, based on factor variable
map<-ggplot(data, aes(Long, Lat, color = Sex)) + geom_polygon(data=w, colour="grey50", fill="grey50", aes(x=long, y=lat, group=group)) + xlab("Longitude") +ylab("Latitude") + ylim(67.5, 76.5) + xlim(-142,-100) +coord_map() +guides(fill = guide_legend(reverse = TRUE))

l <- map  + geom_point(data=data, aes(x=Long, y=Lat, shape=Sex,color = Sex)) + theme_bw()  + coord_map() +guides(fill = guide_legend(reverse = TRUE))+
stat_ellipse(geom="polygon", fill=NA, level = 0.50, type="t", size=2)+
stat_ellipse(geom="polygon", fill=NA, level = 0.75, type="t", linetype=2)+ ggtitle("All1, all bears, all FA")+  scale_color_manual(name="Sex", values=c("blue","red")) + scale_shape_manual(name="Sex", values=c(15:16))
l

Add heat map

map <- ggplot(data, aes(Long,Lat)) + geom_polygon(data=w, colour="grey50", fill="grey50", aes(x=long, y=lat))+coord_map()+ ylim(67.5, 76.5) + xlim(-142,-100)+ geom_point(data=data, aes(Long, Lat))

heat <- map +stat_density2d(aes(fill=..level..,alpha=..level..),geom='polygon',colour=NA, na.rm = TRUE, bins=20,h=10) + scale_fill_continuous(low="green",high="red")  +
labs(fill = "Sampling\nIntensity")  + guides(alpha="none") +geom_point(na.rm=TRUE) + theme(legend.position = c(0.14, 0.65),panel.grid.major = element_line(colour = "white"))
heat

#change number of bands (bandwidth = bins) and number of grid points in each direction (n)
heat <- map +stat_density2d(aes(fill=..level..,alpha=..level..),geom='polygon',colour=NA, na.rm = TRUE, bins=5,h=9) + scale_fill_continuous(low="green",high="red")  +
labs(fill = "Sampling\nIntensity")  + guides(alpha="none") +geom_point(na.rm=TRUE)
heat

#while we're here, change location of legend 
heat <- map +stat_density2d(aes(fill=..level..,alpha=..level..),geom='polygon',colour=NA, na.rm = TRUE, bins=5,h=9) + scale_fill_continuous(low="green",high="red")  +
labs(fill = "Sampling\nIntensity")  + guides(alpha="none") +geom_point(na.rm=TRUE) + theme(legend.position = c(0.1, 0.7),panel.grid.major = element_line(colour = "white"))
heat

#and change background to transparent
heat <- map +stat_density2d(aes(fill=..level..,alpha=..level..),geom='polygon',colour=NA, na.rm = TRUE, bins=5,h=9) + scale_fill_continuous(low="green",high="red")  +
labs(fill = "Sampling\nIntensity")  + guides(alpha="none") +geom_point(na.rm=TRUE) + theme(legend.position = c(0.1, 0.7),panel.grid.major = element_line(colour = "white"), legend.background = element_rect(fill="NA"))
heat

GGMAP

The only difference here is that you can “get_map” and formatting is set up to automatically make it a map (without having to call it a geom_polygon)

geocode("york university")
## Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=york%20university&sensor=false
##         lon      lat
## 1 -79.50187 43.77345
geocode("cn tower", output="all")
## Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=cn%20tower&sensor=false
## $results
## $results[[1]]
## $results[[1]]$address_components
## $results[[1]]$address_components[[1]]
## $results[[1]]$address_components[[1]]$long_name
## [1] "301"
## 
## $results[[1]]$address_components[[1]]$short_name
## [1] "301"
## 
## $results[[1]]$address_components[[1]]$types
## [1] "street_number"
## 
## 
## $results[[1]]$address_components[[2]]
## $results[[1]]$address_components[[2]]$long_name
## [1] "Front Street West"
## 
## $results[[1]]$address_components[[2]]$short_name
## [1] "Front St W"
## 
## $results[[1]]$address_components[[2]]$types
## [1] "route"
## 
## 
## $results[[1]]$address_components[[3]]
## $results[[1]]$address_components[[3]]$long_name
## [1] "Old Toronto"
## 
## $results[[1]]$address_components[[3]]$short_name
## [1] "Old Toronto"
## 
## $results[[1]]$address_components[[3]]$types
## [1] "political"           "sublocality"         "sublocality_level_1"
## 
## 
## $results[[1]]$address_components[[4]]
## $results[[1]]$address_components[[4]]$long_name
## [1] "Toronto"
## 
## $results[[1]]$address_components[[4]]$short_name
## [1] "Toronto"
## 
## $results[[1]]$address_components[[4]]$types
## [1] "locality"  "political"
## 
## 
## $results[[1]]$address_components[[5]]
## $results[[1]]$address_components[[5]]$long_name
## [1] "Toronto Division"
## 
## $results[[1]]$address_components[[5]]$short_name
## [1] "Toronto Division"
## 
## $results[[1]]$address_components[[5]]$types
## [1] "administrative_area_level_2" "political"                  
## 
## 
## $results[[1]]$address_components[[6]]
## $results[[1]]$address_components[[6]]$long_name
## [1] "Ontario"
## 
## $results[[1]]$address_components[[6]]$short_name
## [1] "ON"
## 
## $results[[1]]$address_components[[6]]$types
## [1] "administrative_area_level_1" "political"                  
## 
## 
## $results[[1]]$address_components[[7]]
## $results[[1]]$address_components[[7]]$long_name
## [1] "Canada"
## 
## $results[[1]]$address_components[[7]]$short_name
## [1] "CA"
## 
## $results[[1]]$address_components[[7]]$types
## [1] "country"   "political"
## 
## 
## $results[[1]]$address_components[[8]]
## $results[[1]]$address_components[[8]]$long_name
## [1] "M5V 2T6"
## 
## $results[[1]]$address_components[[8]]$short_name
## [1] "M5V 2T6"
## 
## $results[[1]]$address_components[[8]]$types
## [1] "postal_code"
## 
## 
## 
## $results[[1]]$formatted_address
## [1] "301 Front St W, Toronto, ON M5V 2T6, Canada"
## 
## $results[[1]]$geometry
## $results[[1]]$geometry$location
## $results[[1]]$geometry$location$lat
## [1] 43.64257
## 
## $results[[1]]$geometry$location$lng
## [1] -79.38706
## 
## 
## $results[[1]]$geometry$location_type
## [1] "ROOFTOP"
## 
## $results[[1]]$geometry$viewport
## $results[[1]]$geometry$viewport$northeast
## $results[[1]]$geometry$viewport$northeast$lat
## [1] 43.64392
## 
## $results[[1]]$geometry$viewport$northeast$lng
## [1] -79.38571
## 
## 
## $results[[1]]$geometry$viewport$southwest
## $results[[1]]$geometry$viewport$southwest$lat
## [1] 43.64122
## 
## $results[[1]]$geometry$viewport$southwest$lng
## [1] -79.38841
## 
## 
## 
## 
## $results[[1]]$place_id
## [1] "ChIJmzrzi9Y0K4gRgXUc3sTY7RU"
## 
## $results[[1]]$types
## [1] "establishment"     "point_of_interest" "premise"          
## 
## 
## 
## $status
## [1] "OK"
qmap(location="northamerica", zoom=3)
## Map from URL : http://maps.googleapis.com/maps/api/staticmap?center=northamerica&zoom=3&size=640x640&scale=2&maptype=terrain&language=en-EN&sensor=false
## Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=northamerica&sensor=false
## Warning: `panel.margin` is deprecated. Please use `panel.spacing` property
## instead

qmap(location="york university")
## Map from URL : http://maps.googleapis.com/maps/api/staticmap?center=york+university&zoom=10&size=640x640&scale=2&maptype=terrain&language=en-EN&sensor=false
## Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=york%20university&sensor=false
## Warning: `panel.margin` is deprecated. Please use `panel.spacing` property
## instead

qmap(location="york university", zoom = 14, extent="normal")
## Map from URL : http://maps.googleapis.com/maps/api/staticmap?center=york+university&zoom=14&size=640x640&scale=2&maptype=terrain&language=en-EN&sensor=false
## Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=york%20university&sensor=false

qmap(location="northamerica", zoom=3)
## Map from URL : http://maps.googleapis.com/maps/api/staticmap?center=northamerica&zoom=3&size=640x640&scale=2&maptype=terrain&language=en-EN&sensor=false
## Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=northamerica&sensor=false
## Warning: `panel.margin` is deprecated. Please use `panel.spacing` property
## instead

plot crimes in houston

# first, subset to have only violent crimes
violent_crimes <- subset(crime,offense != "auto theft" & offense != "theft" & offense != "burglary")

# subset area to downtown
violent_crimes <- subset(violent_crimes,
  -95.39681 <= lon & lon <= -95.34188 &
   29.73631 <= lat & lat <=  29.78400)

#make basemap
HoustonMap <- qmap("houston", zoom = 14,color = "bw")
## Map from URL : http://maps.googleapis.com/maps/api/staticmap?center=houston&zoom=14&size=640x640&scale=2&maptype=terrain&language=en-EN&sensor=false
## Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=houston&sensor=false
## Warning: `panel.margin` is deprecated. Please use `panel.spacing` property
## instead
#add layer with crime location data
HoustonMap +geom_point(aes(x = lon, y = lat),data = violent_crimes)
## Warning: Removed 11 rows containing missing values (geom_point).

#Color by type of crime
HoustonMap +geom_point(aes(x = lon, y = lat,colour = offense),data = violent_crimes)
## Warning: Removed 11 rows containing missing values (geom_point).

another heat map example

#make basemap
houston <- get_map(location = "houston", zoom = 14, color = "bw")
## Map from URL : http://maps.googleapis.com/maps/api/staticmap?center=houston&zoom=14&size=640x640&scale=2&maptype=terrain&language=en-EN&sensor=false
## Information from URL : http://maps.googleapis.com/maps/api/geocode/json?address=houston&sensor=false
HoustonMap <- ggmap(houston, base_layer = ggplot(aes(x = lon, y = lat), data = violent_crimes))

#add crimes (stat_density2d) and by offense (facet_wrap)
HoustonMap + stat_density2d(aes(x = lon, y = lat, fill = ..level.., alpha= ..level..),
bins = 5, geom = "polygon",
data = violent_crimes) +scale_fill_gradient(low = "green",high= "red") +facet_wrap(~ offense)
## Warning: Removed 11 rows containing non-finite values (stat_density2d).