r - leaflet heatmap in rmarkdown

tospig

Question

Can you plot a leaflet heatmap in an rmarkdown document?

Example working code

This code will generate a leaflet map with a heatmap when run directly from R

library(rCharts)

## data
dat <- data.frame(Longitude = c(-122.3809, -122.3269, -122.3342, -122.2984, -122.3044, -122.2754),
              Latitude = c(47.66796,47.63436,47.57665,47.71930,47.60616,47.55392),
              intensity = c(10,20,30,40,50,300))

## create JSON for heatmap
## - could also use jsonlite::toJSON
j <- paste0("[",dat[,"Latitude"], ",", dat[,"Longitude"], ",", dat[,"intensity"], "]", collapse=",")
j <- paste0("[",j,"]")

## create leaflet map
leaf_map <- Leaflet$new()
leaf_map$setView(c(47.5982623,-122.3415519), zoom=10)
leaf_map$tileLayer(provider="Acetate.terrain")

## add heatmap plugin
leaf_map$addAssets(jshead = c("http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js"))

## heatmap layer
leaf_map$setTemplate(afterScript = sprintf("
    <script> 
    var addressPoints = %s
    var heat = L.heatLayer(addressPoints).addTo(map)           
    </script>
    ", j
))

## output map
leaf_map

Output:

enter image description here

I have an example of this working in shiny too using tags$ and HTML().

rmarkdown chunk

Using Ramnath's example of embedding rCharts in R Markdown I can get close to creating this in a markdown document, but when this runs it displays the map, but not the heat.

```{r heatMapMarkdown, results='asis', comment=NA, cache=F}

## References
# - http://bl.ocks.org/ramnathv/raw/8084330/ - embedding rCharts in R Markdown

library(rCharts)

dat <- data.frame(Longitude = c(-122.3809, -122.3269, -122.3342, -122.2984, -122.3044, -122.2754),
              Latitude = c(47.66796,47.63436,47.57665,47.71930,47.60616,47.55392),
              intensity = c(10,20,30,40,50,300))


## create JSON for heatmap
## - could also use jsonlite::toJSON
j <- paste0("[",dat[,"Latitude"], ",", dat[,"Longitude"], ",", dat[,"intensity"], "]", collapse=",")
j <- paste0("[",j,"]")

leaf_map <- Leaflet$new()
leaf_map$setView(c(47.5982623,-122.3415519), zoom=10)
leaf_map$tileLayer(provider="Acetate.terrain")

## Add circle:
# leaf_map$marker(c(47.5982623, -122.3415519))

leaf_map$addAssets(jshead = c("http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js"))

leaf_map$setTemplate(afterScript = sprintf("
    <script> 
    var addressPoints = %s
    var heat = L.heatLayer(addressPoints).addTo(map)           
    </script>
    ", j
))

## shows the map, but not the heat...
leaf_map$print('iframesrc', include_assets=TRUE, cdn=TRUE)

```

Is it possible to get the 'heat' to display on the map too?

tospig

I figured this out thanks to the answer to the question How to add an interactive visualisation to R Markdown

First, I create an html document for the <head> section to include a src to the heatmap plugin, and save it in the same directory as my .Rmd file with the name include_js_heatmap.html

<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
<style>
    #map { width: 800px; height: 600px; }
    body { font: 16px/1.4 "Helvetica Neue", Arial, sans-serif; }
    .ghbtns { position: relative; top: 4px; margin-left: 5px; }
    a { color: #0077ff; }
</style> 

<script src = "http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js"></script>

I can then include this in the header of the .Rmd, and write the html to generate the heatmap directly into the body of the document.

To make the heat interactive I can construct the JSON of heat points in a code chunk, then include it in the body of the document with the r ... notation

---
title: heatmapRMarkdown
output:
  html_document:
    self_contained: false
    keep_md: true
    includes:
      in_header: "include_js_heatmap.html"
---

```{r}
dat <- data.frame(Longitude = c(-122.3809, -122.3269, -122.3342, -122.2984, -122.3044, -122.2754),
                  Latitude = c(47.66796,47.63436,47.57665,47.71930,47.60616,47.55392),
                  intensity = c(100,20,30,400,50,3))

j <- paste0("[",dat[,"Latitude"], ",", dat[,"Longitude"], ",", dat[,"intensity"], "]", collapse=",")
j <- paste0("[",j,"]")

```

<div id="map"></div>

<script src="http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js"></script>

<script>
var map = L.map('map').setView([47.5982623,-122.3415519], 12);

var tiles = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
    attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
}).addTo(map);

addressPoints = `r j` ;

var heat = L.heatLayer(addressPoints).addTo(map);
</script>

Update

The <div ...> method will create a directory alongside the .Rmd file with various .html, .js, .css files within it. Once this is created the standard rCharts code will work without the need for the <div...> html code any more:

## create leaflet map
leaf_map <- Leaflet$new()
leaf_map$setView(c(47.5982623,-122.3415519), zoom=10)
leaf_map$tileLayer(provider="Acetate.terrain")

## add heatmap plugin
leaf_map$addAssets(jshead = c("http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js"))

## heatmap layer
leaf_map$setTemplate(afterScript = sprintf("
    <script> 
    var addressPoints = %s
    var heat = L.heatLayer(addressPoints).addTo(map)           
    </script>
    ", j
))

## output map
leaf_map 

Update 2

A slight variation on this which avoids the include is to use the all the relevant html directly in the .Rmd document:

```{r baseMap, results='asis', echo=FALSE, comment=NA, cache=FALSE}
library(rCharts)
dat <- data.frame(Longitude = c(-122.3809, -122.3269, -122.3342, -122.2984, -122.3044, -122.2754),
                  Latitude = c(47.66796,47.63436,47.57665,47.71930,47.60616,47.55392),
                  intensity = c(100,20,30,400,50,3))

j <- paste0("[",dat[,"Latitude"], ",", dat[,"Longitude"], ",", dat[,"intensity"], "]", collapse=",")
j <- paste0("[",j,"]")

```

<!-- add heatmap html-->
<div id="heatmap"></div>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css" />
<script src="http://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.js"></script>
<style>
  #heatmap { width: 800px; height: 600px; }
  body { font: 16px/1.4 "Helvetica Neue", Arial, sans-serif; }
  .ghbtns { position: relative; top: 4px; margin-left: 5px; }
  a { color: #0077ff; }
</style> 
<script src="http://leaflet.github.io/Leaflet.heat/dist/leaflet-heat.js"></script>

<script>
  var heatmap = L.map('heatmap').setView([47.5982623,-122.3415519], 12);
  var tiles = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors',
    }).addTo(heatmap);
  addressPoints = `r j` ;
  var heat = L.heatLayer(addressPoints).addTo(heatmap);
</script>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related