knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

Heatmap demo details

library(monzor)
library(ggmap)
library(dplyr)

## Get all the transactions, expanding the response to include the merchant transactions
transactions <- getTransactions(expand = "merchant")

## We're just interested in the locations and amount, so we trim down the data
locations = transactions$merchant$address
locations$amount = transactions$amount

## Set a universal map zoom level between Google maps and the Stamen map tile retrieval
mapsZoom <- 14

## Geocode a location (in this demo, London) to retrieve the bounding box
googMap <- get_googlemap("London, United Kingdom", zoom = mapsZoom)
bb <- attr(googMap, "bb")

## Filter the transactions to only be within the bounding box
locations <- locations %>%
    filter(!is.na(latitude)) %>%
    filter(
        latitude < bb$ur.lat,
        latitude > bb$ll.lat,
        longitude < bb$ur.lon,
        longitude > bb$ll.lon,
    )

## Retrieve the map using the bounding box and the stamen map type 'toner lite'
transactionsMap <- get_stamenmap(bb2bbox(bb), maptype = "toner-lite", zoom = mapsZoom)
## Draw the density lines, the 'heat' polygons, scale their colour and alpha
ggmap(transactionsMap) +
    geom_density2d(data = locations,
                   aes(x = longitude, y = latitude), size = 0.1) +
    stat_density2d(data = locations,
                   aes(x = longitude, y = latitude, fill = ..level.., alpha = ..level..),
                   size = 0.001, bins = 5, geom = "polygon") +
    scale_fill_gradient(low = "green", high = "red") +
    scale_alpha(range = c(0.2, 0.8), guide = FALSE) +
    geom_point(data = locations,
               aes(x = longitude, y = latitude), size = 0.1)


ryanbateman/monzor documentation built on May 24, 2019, 2:03 a.m.