library(mxmaps)
data("df_mxstate")
df_mxstate$value <- df_mxstate$pop
mxstate_choropleth(df_mxstate,
title = "Total population, by state")
Change the color scale
library(mxmaps)
library(viridis)
library(scales)
df_mxstate$value <- df_mxstate$indigenous / df_mxstate$pop
gg = MXStateChoropleth$new(df_mxstate)
gg$title <- "Percentage of the population that self-identifies as indigenous"
gg$set_num_colors(1)
gg$ggplot_scale <- scale_fill_viridis("percent", labels = percent)
gg$render()
A map with labels for each state
library("geojsonio")
library("ggplot2")
library("rgdal")
library("rgeos")
library("maptools")
library("ggrepel")
library("sf")
df_mxstate$value <- df_mxstate$indigenous / df_mxstate$pop * 100
p <- mxstate_choropleth(df_mxstate,
num_colors = 1,
title = "Percentage of the population that self-identifies as indigenous",
legend = "%")
data("mxstate.topoJSON")
data("df_mxstate")
tmpdir <- tempdir()
# have to use RJSONIO or else the topojson isn't valid
write(RJSONIO::toJSON(mxstate.topoJSON), file.path(tmpdir, "state.topojson"))
states <- topojson_read(file.path(tmpdir, "state.topojson"))
## Reading layer `state' from data source `/tmp/diego/Rtmp9G3tdg/state.topojson' using driver `TopoJSON'
## Simple feature collection with 32 features and 1 field
## geometry type: MULTIPOLYGON
## dimension: XY
## bbox: xmin: -117.124 ymin: 14.5321 xmax: -86.71842 ymax: 32.71863
## CRS: NA
# remove bad polygons
states <- gBuffer(as_Spatial(states), byid=TRUE, width=0)
# make sure the coordinates of the labels are in the correct order
df_mxstate <- cbind(df_mxstate,
data.frame(lon = coordinates(states[match(df_mxstate$region, states$id),])[,1],
lat = coordinates(states[match(df_mxstate$region, states$id),])[,2]))
df_mxstate$group <- df_mxstate$state_abbr
p +
geom_text_repel(data = df_mxstate, aes(lon, lat, label = state_abbr), size = 3,
box.padding = unit(0.1, 'lines'), force = 0.1)
Add a legend for states with NA values
df_mxstate$value <- df_mxstate$indigenous / df_mxstate$pop * 100
df_mxstate$value[1:5] <- NA
mxstate_choropleth(df_mxstate,
num_colors = 1,
title = "Percentage of the population that identifies\nas indigenous",
legend = "%") +
# Add a fake color scale which we'll change to 'no data'
geom_point(data = df_mxmunicipio[1,],
aes(color = "", group = NA, lat = lat, long = long)) +
scale_color_manual(values = NA) +
guides(color=guide_legend("no data",
override.aes=list(color = "black",
shape = 15,
size = 7)))