Using specific variables with spatialpolygons for Leaflet mapping - r

I am trying to produce a map of income levels in various council areas in Sydney using leaflet. While I was able to produce circlemarkers, I have been hoping to produce the same results in polygons.
I have come across a shapefile from Councils in New South Wales, which I have managed to import to R and produce some maps in there, and then I tried merging that spatialpolygondataframe with my income dataframe using the council name, but this wasn't getting me the results that I hoped for. Below is my code, where newobj is my combined dataframe.
leaflet() %>%
addProviderTiles("CartoDB.Positron", options= providerTileOptions(opacity = 0.99)) %>%
addPolygons(data = newobj$`Crimes against the person`,
stroke = FALSE, fillOpacity = 0.5, smoothFactor = 0.5
)
I basically received a few errors in there and could not produce the map.

I actually just managed to find another solution using TMAP package on R, with adding the details of my dataset to the data table of my spatial polygons.

Related

How to map a single US state (MO) county population data using maps package?

I'm having difficulty mapping gradient colors to some county-level population data I have using the base R package maps. I know that colors must be interpolated to the dataframe, but I'm not sure how that is then translated to the map. Here is the code I'm using:
library(dplyr)
require(maps)
my_fake_data <- data_frame(
county = sample(c('list','of','all','counties'),115,T),
county_population = sample(1:1000000,115,T))
grey_black <- colorRampPalette(c('grey50','black'))
map_data <- my_fake_data %>%
arrange(county_population) %>%
mutate(county_population_color = grey_black(nrow(.)))
map('county','missouri',interior = T,fill =T,
col = grey_black(map_data$county_population_color))
How do I tell R to map colors in the correct order? My sense tells me to attach my data to map's internal database, but I can't find the documentation to do it correctly - - or, more likely, I'm just wrong. Any help would be greatly appreciated.
To answer your question, you will need to access the county.fips data frame contained in the maps package. This will have the fips number and the state, county name. This list is in the correct order for mapping. The code example below extracts the Missouri counties and randomly colors a couple for verification:
mocounties<-county.fips[grepl('missouri', county.fips$polyname),]
mocounties$col<-"grey"
mocounties$col[5]<-"red"
mocounties$col[15]<-"green"
mocounties$col[115]<-"blue"
map('county','missouri', interior = T,fill =T,
col = mocounties$col)

TopoJSON choropleth in R/Leaflet?

Is it possible to style a TopoJSON file from its features for a choropleth using R/leaflet? Tried a few things, and I'm not sure if this is impossible with the leaflet package or if I just don't have the syntax right, especially accessing the properties to enter in the pal() function. Here's what I have:
pal<-colorNumeric(palette ="YlOrRd",domain = USAdata$GINI) #USAdata data frame I merged with the spdf before converting it to shp/topojson
map<-leaflet() %>%
addTiles(options=tileOptions(minZoom = 3)) %>%
setMaxBounds(-167.276413,5.499550,-52.233040, 83.162102) %>%
setView(93.85,37.45,zoom =3) %>%
#addGeoJSON(geojson = jso5)
addTopoJSON(topojson=jso, fillColor = ~pal("GINI"))
#addPolygons(data=poly)
this throws up an error:
"Error in UseMethod("doResolveFormula") :
no applicable method for 'doResolveFormula' applied to an object of class "NULL""
I also tried converting it to an R object the topojson with fromJSON() and adding style elements, but this won't load after I try send it back with toJSON().
Not sure if relevant, but the topojson was created from a shapefile made following the instructions here:
with cl:
topojson -o 'USApuma.json' --shapefile-encoding utf8 --id-property=+GEOID10 -p GINI,+STATEFP10,+GEOID10 -- 'usaetest.shp'
then read in with readLines().
Eventually trying to throw this into a shiny app. Here's some examples I've been following.
Do you need to use TopoJSON? If not consider using the tigris package (disclosure: I created and maintain the package). It'll get you access to just about any Census geographic dataset you need, and plays nicely with leaflet. Here's a brief example in line with what you are doing. For example, you can get all PUMAs in the continental US with the following code:
library(readr)
library(tigris)
library(leaflet)
us_states <- unique(fips_codes$state)[1:51]
continental_states <- us_states[!us_states %in% c("AK", "HI")]
pumas_list <- lapply(continental_states, function(x) {
pumas(state = x, cb = TRUE)
})
us_pumas <- rbind_tigris(pumas_list)
I've generated a sample dataset that measures PUMA median household income for this example; the geo_join function from the tigris package can merge the dataset to the spatial data frame us_pumas:
puma_income <- read_csv('http://personal.tcu.edu/kylewalker/data/puma_income.csv')
joined_pumas <- geo_join(us_pumas, puma_income, 'GEOID10', 'GEOID')
We can then plot with Leaflet:
pal <- colorQuantile(palette = 'YlOrRd', domain = joined_pumas$hhincome, n = 7)
leaflet(joined_pumas) %>%
addProviderTiles('CartoDB.Positron') %>%
addPolygons(weight = 0.5, fillColor = ~pal(hhincome),
color = 'lightgrey', fillOpacity = 0.75,
smoothFactor = 0.2) %>%
addLegend(pal = pal,
values = joined_pumas$hhincome)
If you are planning to build a Shiny app, I'd recommend saving out the PUMAs you obtain from tigris first as a .rda file and reading it in with your Shiny script so you don't have to rbind_tigris every time.

Remove unused GEOID in geo_join

I am attempting to plot profitability on top of counties in Minnesota, Iowa, and Nebraska. Using leaflet and tigris, I have been able to plot ALL counties, whether or not I have data for it. This leaves me with a few counties with colors and the rest labeled as NA. Is there a way for me to remove all NA's from my geo_join data so that it just isn't used ala unused Wisconsin areas? I have tried using fortify, but I can't figure out how to determine what county boundaries I'm looking at when I merge the TIGER boundary lines with my County FIPS file in order to remove them.
Here is what my leaflet currently looks like:
My code to get the map is this:
library(tigris)
library(leaflet)
pal <- colorNumeric(c("yellow","dark red"),county$Construction.Cost,na.color="white")
IA_counties <- counties(state="IA", cb=TRUE, resolution ="20m")
MN_counties <- counties(state="MN",cb=TRUE,resolution="20m")
NE_counties <- counties(state="NE",cb=TRUE,resolution="20m")
IA_merged <- geo_join(IA_counties,county,"GEOID", "GEOID")
MN_merged <- geo_join(MN_counties,county,"GEOID","GEOID")
NE_merged <- geo_join(NE_counties,county,"GEOID","GEOID")
popupIA <- paste0("County Projects: ", as.character(paste('$',formatC(format(round(IA_merged$Construction.Cost, 0), big.mark=',', format = 'f')))))
popupMN <- paste0("County Projects: ", as.character(paste('$',formatC(format(round(MN_merged$Construction.Cost, 0), big.mark=',', format = 'f')))))
popupNE <- paste0("County Projects: ", as.character(paste('$',formatC(format(round(NE_merged$Construction.Cost, 0), big.mark=',', format = 'f')))))
leaflet() %>%
addProviderTiles("MapQuestOpen.OSM") %>%
addLegend(pal = pal,
values = IA_merged$Construction.Cost,
position = "bottomright",
title = "County Projects",
labFormat=labelFormat(prefix="$")) %>%
addCircles(lng=yup2$lon, lat=yup2$lat,weight=.75,fillOpacity=0.01,color="red",
radius = 96560) %>%
addCircles(lng=yup2$lon, lat=yup2$lat,weight=.75,fillOpacity=0.01,color="blue",
radius = 193121) %>%
addPolygons(data = IA_counties,
fillColor = ~pal(IA_merged$Construction.Cost),
layerId=1,
fillOpacity = .25,
weight = 0.05,
popup = popupIA)%>%
addPolygons(data=MN_counties,
fillColor=~pal(MN_merged$Construction.Cost),
fillOpacity=0.25,
weight=0.05,
popup = popupMN) %>%
addPolygons(data=NE_counties,
fillColor=~pal(NE_merged$Construction.Cost),
fillOpacity=0.25,
weight=0.05,
popup = popupNE)
I apologize for not including reproducible data, but if needed, please ask. I'm hoping that this is more of a simple na.color= formula solution. The map looks "okay" as of now, but I'd like it if it's possible to not have to make the fillOpacity so light so the NA counties don't stand out.
Thanks for any and all help and please, let me know if you have any questions!
I'm the creator of the tigris package. Thanks so much for using it! In the development version of tigris on GitHub (https://github.com/walkerke/tigris), I've added an option to geo_join to accommodate inner joins, which would remove the unmatched data entirely from the resultant spatial data frame (if this is what you are looking for). You can also supply a common merge column name as a named argument to the new by parameter if you want. For example:
IA_merged <- geo_join(IA_counties, county, by = "GEOID", how = "inner")
should work. I'm still testing but I'll probably submit this update to CRAN in January.
So, embarrassingly, the answer to this question was as simple as I had hoped. I tweaked the following na.color code and it worked exactly as I wanted.
pal <- colorNumeric(c("yellow","dark red"),county$Construction.Cost,na.color="transparent")

Plotting regions and adding color in leaflet R

I need to plot a map of Denmark divided into regions (there are 5: Region Nordjylland, Midtjylland, Sydjylland, Sjælland and Hovedstaden) and then color the regions such that the different regions stand out clearly. I have to use leaflet, since it has other features, that I will use later. I found a map on naturalearthdata.com, that I think I can use, but I can't figure out how to color (or even indicate) the regions. The code I tried is below
library(rgdal)
library(leaflet)
download.file(file.path('http://www.naturalearthdata.com/http/',
'www.naturalearthdata.com/download/50m/cultural',
'ne_50m_admin_1_states_provinces_lakes.zip'),
f <- tempfile())
unzip(f, exdir=tempdir())
world <- readOGR(tempdir(), 'ne_50m_admin_1_states_provinces_lakes', encoding='UTF-8')
DK <- subset(world, name=="Denmark")
leaflet() %>% addTiles() %>% addTopoJSON(DK, weight = 1, color = "#444444", fill = TRUE)
How does one use the naturalearthdata.com data to plot regions/states/provinces of different countries? I have seen a very nice example at
http://www.56n.dk/kort/dk2050kort_age.html
but there is no sample code available.
I have also found a very nice example here: https://rpubs.com/walkerke/leaflet_choropleth - but I need a map of Denmark.
UPDATE: I have found a shapefile at http://www.kortforsyningen.dk which does the trick. So now my question is how do I combine my own data with a shapefile and plot it in leaflet? If I just put
DK <- readOGR(".../shape", layer="REGION")
leaflet(data=DK)
I get a blank screen...

R Leaflet doesn't add all markers

I'm trying to follow the example in the link below to create a map with all the markers
Tutorial: How to put dots on a Leaflet map with R
The source file is below
https://www.dropbox.com/s/az1yolknqwoxhb4/test_file.csv?dl=0
And the code that I tried
library(dplyr)
library(leaflet)
test_map <- read.csv("test_file.csv", header = TRUE, stringsAsFactors = FALSE)
m <- leaflet(test_map) %>% addTiles('http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png',
attribution='Map tiles by Stamen Design, CC BY 3.0 — Map data © OpenStreetMap')
m %>% setView()
m %>% addCircles(~long, ~lat,
popup=test_map$index,
weight = 3,
color="#ffa500", stroke = TRUE, fillOpacity = 0.8)
I was able to create the map
However, the map only shows a fraction of points, since the data I have has locations all over Canada. When I tried to sub-select a city say like Toronto then some of the missing points shows up.
I'm not sure if i'm doing anything wrong or if this is a bug.I wonder if there's anyway for me to fix this problem or is there an alternative way to achieve a similar map?
Thank you :)
There are NA values in test_map variable.
add
test_map <- na.omit(test_map)
after reading csv.
By this method i have more markers than your image.

Resources