library(tidyverse)
library(knitr)
library(dplyr)
library(leaflet)
library(ggmap)
library(rgdal)
As a continuation from the first assignment I have mapped towns in Maine that had wells with high levels of both arsenic and fluoride.
The first step after loading various packages, was to get the data from the original assignment and filter for only the towns that had both toxins above guidelines in their well water. The state was added to the town names to create an address that could be geocoded using ggmaps.
mapped<-relevantData %>% filter(group=="Both toxins above guidelines")
mapped <-mutate(mapped,addr=paste(mapped$location,",ME"))
mapped
The co-ordinates of each location were linked to the existing information in a new data frame called mapped_loc. As there are 158 towns in the set, the data frame was written to a csv file to avoid running multiple duplicate queries in the future.
mapped_loc <- geocode(mapped$addr)
head(mapped_loc)
mapped_loc <- bind_cols(mapped, mapped_loc)
write.csv(mapped_loc,"C:/Users/Mahom/Desktop/Data Management and Analysis/unit 8/mapped_loc.csv",row.names = TRUE)
Next the pin popups are set up to include the percent of wells that are above the toxin guidelines for that location.
pops <- paste("<strong>Name: ",
mapped_loc$location,
"</strong><br>",
"% above arsenic guidelines: ",
mapped_loc$above_As_guideline,
"</strong><br>",
"% above flouride guidelines ",
mapped_loc$above_F_guideline)
head(pops)
Everything is setup to create the map using leaflet!
map1 <- leaflet() %>%
addTiles() %>%
addMarkers(lng = mapped_loc$lon, lat = mapped_loc$lat, popup = pops)
map1
The map looks crowded, so I added a command to cluster the markers. The resulting map looks better.
map2 <- leaflet() %>%
addTiles() %>%
addMarkers(lng = mapped_loc$lon, lat = mapped_loc$lat, popup = pops,clusterOptions = markerClusterOptions())
map2
This is a map showing the route between the towns with the highest and lowest arsenic values.
max<-mapped_loc[which.max(mapped_loc$above_As_guideline),]
min<-mapped_loc[which.min(mapped_loc$above_As_guideline),]
route_df <- route(max$addr, min$addr, mode = "driving", structure = "route")
map3 <- leaflet() %>%
addTiles() %>%
addMarkers(lng = max$lon, lat = max$lat, popup = paste("<strong>Name: ",max$location,"</strong><br>","% above arsenic guidelines: ",max$above_As_guideline,"</strong><br>","% above flouride guidelines ",max$above_F_guideline)) %>%
addMarkers(lng = min$lon, lat = min$lat, popup = paste("<strong>Name: ",min$location,"</strong><br>","% above arsenic guidelines: ",min$above_As_guideline, "</strong><br>","% above flouride guidelines ",min$above_F_guideline)) %>%
addPolylines(lng = route_df$lon, lat = route_df$lat, fill=FALSE, color="purple")
map3
This report was completed using ggmaps. D. Kahle and H. Wickham. ggmap: Spatial Visualization with ggplot2. The R Journal, 5(1), 144-161. URL http://journal.r-project.org/archive/2013-1/kahle-wickham.pdf