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

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)

Related

Mapping with shapefiles in R

I have a shapefile with tons of different polygons representing different bodies of water (lakes, rivers etc.)
I would like to create a map of certain polygons. All of the current examples I could find only show how to plot shapefiles with ONLY the polygons wanted in them. So I am not sure how to only plot the specific polygons.
Link to the shapefile: https://hub.arcgis.com/datasets/esri::usa-detailed-water-bodies/explore?location=45.461044%2C-84.374110%2C10.71
I would like to plot OBJECTID295061, 295018, and 295017
Current code:
library(sf)
shp = st_read("USA_Detailed_Water_Bodies.shp")
ggplot(data = shp) +
geom_sf()+
coord_sf()+
theme_bw()
Current map:
Assuming OBJECTID is a numeric column of your data:
library(sf)
shp = st_read("USA_Detailed_Water_Bodies.shp")
Then you can make an "area of interest" subset like this:
aoi = shp[shp$OBJECTID %in% c(295061, 295018, 295017),]
Then make your plot using aoi.
If the OBJECTID numbers are the same as the row numbers you can select by row:
aoi = shp[c(295061, 295018, 295017),]
but I'm not sure because no time for a 250Mb download right now but I think this is correct.
Spatial dataframes from sf behave mostly like regular data frames, with a few weird exceptions. But for selecting rows and columns its not very different.

How to fix incorrect automatic labels on a map (tmap)

I have a point shapefile with cities (CitiesPoints), and a dataframe that assigns a number of libraries to some of those cities (df; the data is fictitious). I also have a polygon shapefile for the background.
I joined those files to create a map in which a point is generated for each city that has libraries, and the size of the point is determined by the number of libraries it has.
df$CityCode <- as.factor(df$CityCode)
Joint <- CitiesPoints %>%
left_join(df, by=c("link"="CityCode"))
tmap_mode("view")
tm_shape(Background) +
tm_borders() +
tm_shape(Joint) + tm_symbols(id = "localidad",
size = "BIBLIO",
col = "brown1")
However, when I hover over those points with the mouse, the city name shown is incorrect.
Apparently, the top rows in the shape file (including those with no libraries, NA) are the ones being used to assign the labels.
Example
The correct label for this point should be “Rafaela”.
You can download the files I used here: Files
I would really appreciate the help!
I found a way to fix it. I created a new shapefile only containing the rows corresponding to the citys which have libraries.
Joint$BIBLIO[is.na(Joint$BIBLIO)] <- 0
JOINT2 = filter(Joint,BIBLIO>0)
Using this new shapefile, the automatic labels shown are now correct.

Mapping my data to a Zip Code area map in R

My data is like this:
ZIPcode Cases longi lati
43613 1 -83.604452 41.704307
44140 1 -81.92148 41.48982
46052 1 -86.470531 40.051603
48009 22 -83.213883 42.544619
48017 6 -83.151815 42.535396
48021 7 -82.946167 42.463894
48025 19 -83.265758 42.523195
I want to get a map similar to this (if you can see it) in R. The outline should be zipcodes and the shading should be according to number of cases, darker as cases increase.
I'm very new to R. Tried a lot of code I found online but can't get what I want. Any help is appreciated. Can this be done in base SAS ?
Thank you!
enter image description here
Definetly you can do it in R, I put together a reprex (reproducible example) for you. Key points:
You need to load into R a .shp file (or .geojson, .gpkg, etc.). That is an actual file with the outline of your map. For ZIPCODES I found a R package, tigris, that does that for you, if not you'll need to load it by yourself.
For handling mapping objects (load, transform, .etc), sf package is your best friend.
For plotting, in this example I used cartography, but you can use several different package, as ggplot2 or tmap.
Last line is that, given your data (and if I didn't get the ZIPCODEs wrong), a map as the one you shown (choropleth map) maybe is not the best options. Have a look here to see other alternatives.
library(sf) #Overall handling of sf objects
library(cartography) #Plotting maps package
#1. Create your data
yourdata <- data.frame(ZCTA5CE10=c("43613", "44140", "46052",
"48009","48017", "48021","48025"),
Cases=c(1,1,1,22,6,7,19)
)
#2. Download a shapefile (shp,gpkg,geojson...)
library(tigris) #For downloading the zipcode map
options(tigris_use_cache = TRUE)
geo <- st_as_sf(zctas(cb = TRUE, starts_with = yourdata$ZCTA5CE10))
#Overall shape of USA states
states <- st_as_sf(states(cb=TRUE))
#For plotting, all the maps should have the same crs
states=st_transform(states,st_crs(geo))
#3. Now Merge your data
yourdata.sf=merge(geo,yourdata)
#4. Plotting
par(mar=c(1,1,1,1))
ghostLayer(yourdata.sf)
plot(st_geometry(states), add=TRUE)
choroLayer(yourdata.sf,
var="Cases",
add=TRUE,
border = NA,
legend.pos = "right",
legend.frame = TRUE)
layoutLayer(title = "Cases by ZIPCODE",
theme = "blue.pal",
scale = FALSE,
sources = "Source; your question on SO",
author = "by dieghernan, 2020"
)
Created on 2020-02-27 by the reprex package (v0.3.0)

Colorize the map of Russia depending on the variable in R

I have a map of Russia with regional subdivision
library(raster)
data <- getData('GADM', country='RUS', level=1)
http://www.gks.ru/bgd/regl/B16_14p/IssWWW.exe/Stg/d01/08-01.doc
The link is to a Word.doc with data (table) on crime rates for Russian regions. I can extract this data and use it in R. I want to take 2015 year and colorize regions on the map depending on the crime rate (also add a legend). How can I do this? The problem is that names of regions are sometimes different in the shape file (NL_NAME_1) and in the data from www.gks.ru.
I also have this code for graph that I need, except that here we have meaningless colors:
library(sp)
library(RColorBrewer)
data$region <- as.factor(iconv(as.character(data$NAME_1)))
spplot(data, "region", xlim=c(15,190), ylim=c(40,83),
col.regions=colorRampPalette(brewer.pal(12, "Set3"))(85), col = "white")
If I understand your question properly, you just need to add your data to the spatial object for making colors meaningful.
Note, please, that the data is a reserved word in R. So, it's better to modify a little your variable name:
geo_data <- getData('GADM', country = 'RUS', level = 1)
Let's emulate some data to demonstrate a visualization strategy:
set.seed(23)
geo_data#data["data_to_plot"] <- sample(1:100, length(geo_data#data$NAME_1))
Using a default GADM projection would cut the most eastern part of the country. A simple transformation helps to fit the whole area to a plot:
# fit Russian area inside the plot
geo_data_trsf <- spTransform(geo_data, CRS("+proj=longlat +lon_wrap=180"))
Draw the map selecting data_to_plot instead of region:
max_data_val <- max(geo_data_trsf#data$data_to_plot)
spplot(geo_data_trsf, zcol = "data_to_plot",
col.regions = colorRampPalette(brewer.pal(12, "Set3"))(max_data_val),
col = "white")
The plot limits are adjusted automatically for the transformed spatial data geo_data_trsf, making possible to omit xlim and ylim.
As for the problem with the names, I can't provide any ready-to-use solution. Obviously, the regions' names of NL_NAME_1 need some additional treatment to use them as labels. I think, it would be better to use NAME_1 as an identifier in your code to ensure that it'll be no troubles with encoding. The NL_NAME_1 column is perfectly suitable to set the correspondence between your Word-data and the data inside the spatial object geo_data.

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...

Resources