CARTO and R-Leaflet

CARTO

  1. Meet CARTO - a platform that offers an intuitive interface to a fast PostgreSQL database with PostGIS extensions.
  • If you haven’t, set up an account through MIT! We have an enterprise account.
  1. I’ve hosted two tables publically on my CARTO account - these should look familiar! g_all_stategrid and vmt_hh-results.
  • This is, in most ways, the same as having them uploaded to the cronpgsql.mit.edu server we’ve been using in previous labs.
  • We can hit this database with SQL queries and draw data into Python or R, or use CARTO’s GUI interface.
    • Note: CARTO’s built-in functionality is fickle - they’re notorious for being a little inconsistent with what is available.
  1. Let’s create a new map using the CARTO interface.
  • Select the map data. When it is selected, you can explore the data (including running SQL queries), and you can create a map. Create a map!
  • Note how fast this loads! So fast! This is because much of the rendering work is taken care of on the server side.
  1. Let’s join a table. Click on the new g_all_stategrid layer. Click ‘Analysis’, and select ‘Join Columns from 2nd Layer’. Choose appropriate fields in the resulting prompt (g250m and g250m_id).
  2. Now, let’s explore - we can, for example, run queries, subset our data, and do tests for spatial autocorrelation using Moran’s I.

R Leaflet

  1. Leaflet is a titanically popular, lightweight JavaScript package designed to simplify web mapping, developed by Vladamir Agafonkin and collaborators since 2011. It’s so popular that users of other languages are beginning to write wrappers that allow you to send data from data science and statistical computing environments (R, Python) to Leaflet maps with a minimum amount of pain.
  2. One of these wrappers is Leaflet for R, developed by Joe Cheng of RStudio. Let’s take some data from our CARTO database and make a web map in VERY FEW lines of code.
library("sp")
library("rCartoAPI")
library("leaflet")
library("geojsonio")
library("rcartoapi")

sql_inquiry_save_geojson("SELECT * FROM g_hh_results", "~/Desktop/CARTO-RLeaflet/g_hh_results.geojson")



vmt_results <- geojsonio::geojson_read("~/Desktop/CARTO-RLeaflet/g_hh_results.geojson", what = "sp")

pal <- colorNumeric("viridis", NULL)
leaflet(vmt_results) %>%
  addTiles() %>%
  addPolygons(stroke = FALSE, smoothFactor = 0.3, fillOpacity = 0.8, fillColor = ~pal(right_fit_hh)) %>%
  addLegend(pal = pal, values = ~right_fit_hh, opacity = 0.8)