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")
Related
I made some interactive heatmaps using leaflet (particularly the addHeatmap() command from the leaflet.extras package) and shiny. Having created a desired map, I would like to add a legend to it.
What I am interested in is a "rgb" legend, based on density values deduced by addHeatmap() from pure long/lat coords.
What I need is something like this map - https://www.patrick-wied.at/static/heatmapjs/example-legend-tooltip.html - unfortunately I have no knowledge of JS and can't rewrite this code in terms of R/include the right fragment of JS code for my problem.
What I tried so far is the addLegend() command, which does not give the desired result, as in this case I would need to specify a variable for which the legend would be prepared. I also tried to extract the color range and assigned values from created leaflet object, however with no success.
Here's link to full data to run the reproducible example on:
https://drive.google.com/file/d/1h3jL_PU6DGTtdIWBK02Tt37R7IB2ArH9/view
And here's top 20 records:
structure(list(latitude = c(30.309522, 30.24429616, 30.30038194,
30.27752338, 30.23294081, 30.23038507,
30.34285933, 30.24962237, 30.26594744,
30.20515821, 30.22363485, 30.2759184,
30.28283226, 30.33816909, 30.26611565,
30.18835401, 30.26704789, 30.27456699,
30.19237135, 30.1925213),
longitude = c(-97.73171047, -97.77446858, -97.77885789,
-97.71919076, -97.58937812, -97.76581095,
-97.73598704, -97.72215443, -97.74144275,
-97.8782895, -97.78329845, -97.71321066,
-97.70820152, -97.82413058, -97.7327258,
-97.81606795, -97.68989589, -97.7580592,
-97.7816127, -97.73138523)),
.Names = c("latitude", "longitude"), row.names =
c(NA, 20L), class = "data.frame")
Here's an example code, which I'd like to extend by the mentioned functionality:
library(magrittr)
library(leaflet)
library(leaflet.extras)
data <- read.csv('DATA.csv')
leaflet(data) %>%
addTiles(group="OSM") %>%
addHeatmap(group="heat", lng = ~longitude, lat = ~latitude, max=.5, blur = 60)
And here is the result of that code (on whole dataset):
https://i.stack.imgur.com/6VFNC.jpg
So to sum up what I would like to do: based on such picture I would like to extract the range of the drawn colors along with values assigned to them, and draw legend using that information.
Is there something I am missing? It looks like a pretty simple issue, but I've been struggling to find a solution for past few hours.
Thanks in advance for any help!
EDIT: extended the reproducible example.
Your sample data does not have any values to it to actually map a density overlay.
You can specify the number of bins with colorBin() and then specify those bins with your pal function. You can set the bins differently depending on your needs at the data_values distributions. The help section of colorBin() is helpful in identifying the correct parameters for your needs.
bins <- c(0,1,2,3,4)
pal <- colorBin("Spectral", domain = data_value, bins = bins, na.color = "transparent")
m <-leaflet() %>%
addTiles() %>%
addHeatmap(lng= long_cords, lat = lat_cords, intensity = data_value,
blur = 20, max = 400, radius = 15, cellSize = 3) %>%
addLegend(pal = pal, values = data_value,
title="Heat map legend")
You'll have to play around with the addHeatmap arguments to get an the right transparency and density settings.
The code below is reproducible - it builds the map of the world using leaflet.
I am really not interested in Antarctica and I am more interested in Scandinavia :)
Any way to cut Antarctica or at least force it to be always at the bottom of the map - so that the center of the map is farther north?
Thanks a lot for any pointers!
library(leaflet)
library(rnaturalearth)
countries <- rnaturalearth::countries110
goodnames <- countries$name
goodnames[goodnames %in% goodnames[32]] <- "Ivory Coast"
countries$name[32] <- goodnames[32]
mymap <- leaflet(countries, options = leafletOptions(minZoom = 2))
myvalues <- 1:177
mycolors <- colorNumeric(palette = c("#fee6ce","#e6550d"),
domain = myvalues)(myvalues)
mymap %>%
addPolygons(stroke = FALSE, smoothFactor = 0.2, fillOpacity = 1,
color = ~mycolors,
label = countries$name)
You can use setView to set the initial viewing point to any location of your choosing. If you want this map to focus on Scandinavia on opening, you can do...
mymap <- leaflet(countries, options = leafletOptions(minZoom = 2)) %>% setView(lng=18.6435,lat=60.1282,zoom=2)
The coordinates are simply from searching 'Sweden coordinates' on Google. You can use a site such as https://www.latlong.net/ to help you pick an appropriate center point.
Unfortunately 'rnaturalearth' is not (yet) available fpr R 3.4.2 and I have just updated one second ago so I can't prove my answer. But as you're asking for any pointer -
I use the 'rworldmap' package and take out Antarctica by excluding it after the map is defined by the package.
According to this my suggestion to your code would be:
mymap <- mymap[-which(row.names(mymap)=='Antarctica'),]
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)
I hope you can help me. I have created a choropleth Map with Leaflet. I merged my (dataframe with countries and a random score) and a Shapefile with the Polygon data. So far it is working, however if I implement it in R-Shiny, the map is showing, but with no color. There is also no error showing. Anyone knows why?
My code:
ui <- fluidPage(
leafletOutput("map")
)
shinyServer(function(input, output) {
output$map <- renderLeaflet({
test_map
})
})
global.R
tmp <- tempdir()
url <- "http://www.naturalearthdata.com/http//www.naturalearthdata.com/download/50m/cultural/ne_50m_admin_0_countries.zip"
file <- basename(url)
download.file(url, file)
unzip(file, exdir = tmp)
world <- readOGR(dsn = tmp, layer = "ne_50m_admin_0_countries", encoding = "UTF-8")
data <- data.frame(Code = c("AR", "AU", "BE", "BR"),
Score = c(0.01, -0.05, 0.15, -0.22))
world <- merge(world, data,
by.x = "iso_a2",
by.y = "Code",
sort = FALSE)
pal <- colorNumeric(
palette = "RdYlGn",
domain = world$Score
)
test_map <- leaflet(data = world) %>%
addTiles() %>%
addPolygons(fillColor = ~pal(Score),
fillOpacity = 0.9,
color = "#BDBDC3",
weight = 1)
I know this is an old question and I'm not sure whether this will help or not, but I believe I had a similar problem to you which was just solved.
In my case, I had no trouble displaying polygon colours within Rstudio on my own PC, but certain web browsers and older versions of Rstudio refused to fill polygons with colours, even though all other aspects of the map worked fine.
The problem was that my colour palette consisted of a vector of hex codes with an alpha channel (the last couple of digits, specifying transparency). Removing the alpha channel from the hex codes solved my problem. It may be worth checking whether your colour vectors include alpha and if so, removing it with something like gsub(".{2}$","",your_colour_vector) as per the answer to my own problem (link above).
It doesn't look like your colours include alpha in your sample code but maybe it's a problem in your full code. That would explain why the sample code works but the full code doesn't. Might be something to look into anyway? Sorry I can't help more, I know this is a bit of a shot in the dark and not a full solution.
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.