Chapter 6 Maps
6.1 Choropleth Maps
6.1.1 Choropleth Map Using GeoJSON
library(plotly)
library(rjson)
<- 'https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json'
url <- rjson::fromJSON(file=url)
counties <- "https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv"
url2<- read.csv(url2, colClasses=c(fips="character"))
df <- list(
g scope = 'usa',
projection = list(type = 'albers usa'),
showlakes = TRUE,
lakecolor = toRGB('white')
)<- plot_ly()
fig <- fig %>% add_trace(
fig type="choropleth",
geojson=counties,
locations=df$fips,
z=df$unemp,
colorscale="Viridis",
zmin=0,
zmax=12,
marker=list(line=list(
width=0)
)
)<- fig %>% colorbar(title = "Unemployment Rate (%)")
fig <- fig %>% layout(
fig title = "2016 US Unemployment by County"
)
<- fig %>% layout(
fig geo = g
)
fig
6.1.2 Indexing by GeoJSON Properties
library(plotly)
library(rjson)
<- 'https://raw.githubusercontent.com/plotly/datasets/master/election.geojson'
url <- rjson::fromJSON(file=url)
geojson <- "https://raw.githubusercontent.com/plotly/datasets/master/election.csv"
url2<- read.csv(url2)
df <- list(
g fitbounds = "locations",
visible = FALSE
)<- plot_ly()
fig <- fig %>% add_trace(
fig type="choropleth",
geojson=geojson,
locations=df$district,
z=df$Bergeron,
colorscale="Viridis",
featureidkey="properties.district"
)<- fig %>% layout(
fig geo = g
)<- fig %>% colorbar(title = "Bergeron Votes")
fig <- fig %>% layout(
fig title = "2013 Montreal Election"
) fig
6.1.3 Customize choropleth chart
library(plotly)
<- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/2011_us_ag_exports.csv")
df $hover <- with(df, paste(state, '<br>', "Beef", beef, "Dairy", dairy, "<br>",
df"Fruits", total.fruits, "Veggies", total.veggies,
"<br>", "Wheat", wheat, "Corn", corn))
# give state boundaries a white border
<- list(color = toRGB("white"), width = 2)
l # specify some map projection/options
<- list(
g scope = 'usa',
projection = list(type = 'albers usa'),
showlakes = TRUE,
lakecolor = toRGB('white')
)
<- plot_geo(df, locationmode = 'USA-states')
fig <- fig %>% add_trace(
fig z = ~total.exports, text = ~hover, locations = ~code,
color = ~total.exports, colors = 'Purples'
)<- fig %>% colorbar(title = "Millions USD")
fig <- fig %>% layout(
fig title = '2011 US Agriculture Exports by State<br>(Hover for breakdown)',
geo = g
)
fig
6.1.4 World Choropleth Map
<- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')
df
# light grey boundaries
<- list(color = toRGB("grey"), width = 0.5)
l
# specify map projection/options
<- list(
g showframe = FALSE,
showcoastlines = FALSE,
projection = list(type = 'Mercator')
)
<- plot_geo(df)
fig <- fig %>% add_trace(
fig z = ~GDP..BILLIONS., color = ~GDP..BILLIONS., colors = 'Blues',
text = ~COUNTRY, locations = ~CODE, marker = list(line = l)
)<- fig %>% colorbar(title = 'GDP Billions US$', tickprefix = '$')
fig <- fig %>% layout(
fig title = '2014 Global GDP<br>Source:<a href="https://www.cia.gov/library/publications/the-world-factbook/fields/2195.html">CIA World Factbook</a>',
geo = g
)
fig
6.2 Scatter Plots on Maps
6.2.1 Basic Scatter on Map
library(plotly)
<- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2011_february_us_airport_traffic.csv')
df
# geo styling
<- list(
g scope = 'usa',
projection = list(type = 'albers usa'),
showland = TRUE,
landcolor = toRGB("gray95"),
subunitcolor = toRGB("gray85"),
countrycolor = toRGB("gray85"),
countrywidth = 0.5,
subunitwidth = 0.5
)
<- plot_geo(df, lat = ~lat, lon = ~long)
fig <- fig %>% add_markers(
fig text = ~paste(airport, city, state, paste("Arrivals:", cnt), sep = "<br />"),
color = ~cnt, symbol = I("square"), size = I(8), hoverinfo = "text"
)<- fig %>% colorbar(title = "Incoming flights<br />February 2011")
fig <- fig %>% layout(
fig title = 'Most trafficked US airports<br />(Hover for airport)', geo = g
)
fig
6.2.2 Style Scatter Map Layout
library(plotly)
<- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2015_06_30_precipitation.csv')
df
# change default color scale title
<- list(colorbar = list(title = "Total Inches"))
m
# geo styling
<- list(
g scope = 'north america',
showland = TRUE,
landcolor = toRGB("grey83"),
subunitcolor = toRGB("white"),
countrycolor = toRGB("white"),
showlakes = TRUE,
lakecolor = toRGB("white"),
showsubunits = TRUE,
showcountries = TRUE,
resolution = 50,
projection = list(
type = 'conic conformal',
rotation = list(lon = -100)
),lonaxis = list(
showgrid = TRUE,
gridwidth = 0.5,
range = c(-140, -55),
dtick = 5
),lataxis = list(
showgrid = TRUE,
gridwidth = 0.5,
range = c(20, 60),
dtick = 5
)
)
<- plot_geo(df, lat = ~Lat, lon = ~Lon, color = ~Globvalue)
fig <- fig %>% add_markers(
fig text = ~paste(df$Globvalue, "inches"), hoverinfo = "text"
)<- fig %>% layout(title = 'US Precipitation 06-30-2015<br>Source: NOAA', geo = g)
fig
fig
6.3 Mapbox Density
6.3.1 Mapbox Access Token
library(plotly)
= read.csv('https://raw.githubusercontent.com/plotly/datasets/master/earthquakes-23k.csv')
quakes
<- quakes
fig <- fig %>%
fig plot_ly(
type = 'densitymapbox',
lat = ~Latitude,
lon = ~Longitude,
coloraxis = 'coloraxis',
radius = 10)
<- fig %>%
fig layout(
mapbox = list(
style="stamen-terrain",
center= list(lon=180)), coloraxis = list(colorscale = "Viridis"))
fig
6.4 Mapbox Layers
6.4.1 OpenStreetMap Tiles, no Token Needed
library(plotly)
= read.csv("https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv")
us_cities
<- us_cities
fig <- fig %>%
fig plot_ly(
lat = ~lat,
lon = ~lon,
marker = list(color = "fuchsia"),
type = 'scattermapbox',
hovertext = us_cities[,"City"])
<- fig %>%
fig layout(
mapbox = list(
style = 'open-street-map',
zoom =2.5,
center = list(lon = -88, lat = 34)))
fig
6.4.2 Base Map Below A Trace: No Token Needed
library(plotly)
= read.csv("https://raw.githubusercontent.com/plotly/datasets/master/us-cities-top-1k.csv")
us_cities
<- us_cities
fig <- fig %>%
fig plot_ly(
lat = ~lat,
lon = ~lon,
type = "scattermapbox",
hovertext = us_cities[,"City"],
marker = list(color = "fuchsia"))
<- fig %>%
fig layout(mapbox= list(
style = "white-bg",
zoom = 3,
center = list(lon = -93 ,lat= 41),
layers = list(list(
below = 'traces',
sourcetype = "raster",
source = list("https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}")))))
fig
6.5 Bubble Maps
6.5.1 United States Bubble Map
library(plotly)
<- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_us_cities.csv')
df
$q <- with(df, cut(pop, quantile(pop)))
dflevels(df$q) <- paste(c("1st", "2nd", "3rd", "4th", "5th"), "Quantile")
$q <- as.ordered(df$q)
df
<- list(
g scope = 'usa',
projection = list(type = 'albers usa'),
showland = TRUE,
landcolor = toRGB("gray85"),
subunitwidth = 1,
countrywidth = 1,
subunitcolor = toRGB("white"),
countrycolor = toRGB("white")
)
<- plot_geo(df, locationmode = 'USA-states', sizes = c(1, 250))
fig <- fig %>% add_markers(
fig x = ~lon, y = ~lat, size = ~pop, color = ~q, hoverinfo = "text",
text = ~paste(df$name, "<br />", df$pop/1e6, " million")
)<- fig %>% layout(title = '2014 US city populations<br>(Click legend to toggle)', geo = g)
fig
fig