Choose what data will be mapped. Create columns for percents and margins.
nhdata$SandersMarginVotes <- nhdata$Sanders - nhdata$Clintonnhdata$SandersPct <- (nhdata$Sanders) / (nhdata$Sanders + nhdata$Clinton) # Will use formatting later to multiply by a hundrednhdata$ClintonPct <- (nhdata$Clinton) / (nhdata$Sanders + nhdata$Clinton)nhdata$SandersMarginPctgPoints <- nhdata$SandersPct - nhdata$ClintonPct
Read in the shapefile for US states and counties.
library(raster)
Warning: package 'raster' was built under R version 4.2.3
Attaching package: 'raster'
The following object is masked from 'package:dplyr':
select
library(rgdal)
Warning: package 'rgdal' was built under R version 4.2.3
Please note that rgdal will be retired during 2023,
plan transition to sf/stars/terra functions using GDAL and PROJ
at your earliest convenience.
See https://r-spatial.org/r/2022/04/12/evolution.html and https://github.com/r-spatial/evolution
rgdal: version: 1.6-5, (SVN revision 1199)
Geospatial Data Abstraction Library extensions to R successfully loaded
Loaded GDAL runtime: GDAL 3.5.2, released 2022/09/02
Path to GDAL shared files: C:/Users/funne/AppData/Local/R/win-library/4.2/rgdal/gdal
GDAL binary built with GEOS: TRUE
Loaded PROJ runtime: Rel. 8.2.1, January 1st, 2022, [PJ_VERSION: 821]
Path to PROJ shared files: C:/Users/funne/AppData/Local/R/win-library/4.2/rgdal/proj
PROJ CDN enabled: FALSE
Linking to sp version:1.6-0
To mute warnings of possible GDAL/OSR exportToProj4() degradation,
use options("rgdal_show_exportToProj4_warnings"="none") before loading sp or rgdal.
Some legend labels were too wide. These labels have been resized to 0.62, 0.62, 0.62, 0.57, 0.53. Increase legend.width (argument of tm_layout) to make the legend wider and therefore the labels larger.
qtm(nhmap, "SandersMarginPctgPoints")
For more control over look and feel, use the tm_shape() function:
Some legend labels were too wide. These labels have been resized to 0.62, 0.62, 0.62, 0.57, 0.53. Increase legend.width (argument of tm_layout) to make the legend wider and therefore the labels larger.
Same code as above, but store the static map in a variable, and change the theme to “classic” style:
nhstaticmap <-tm_shape(nhmap) +tm_fill("SandersMarginVotes", title="Sanders Margin, Total Votes", palette ="viridis") +#I like viridistm_borders(alpha=.5) +tm_text("NAME", size=0.8) +tm_style("classic")
View the map.
nhstaticmap
Some legend labels were too wide. These labels have been resized to 0.62, 0.62, 0.62, 0.57, 0.53. Increase legend.width (argument of tm_layout) to make the legend wider and therefore the labels larger.
Save the map to a jpg file with tmap’s tmap_save():