R overlay counties (or othr options for county_choropleth) - r

Using some code I've gotten from StackOverflow, I would like to shade a map but also have the county name as well.
In a perfect world, I'd like to be able to show ONLY the top and bottom 5 county names and as an additional twist I'd like the high names in red and low names in black.
But I'm having enough trouble getting any names on or finding any examples of other options to add.
I'm new to R and not sure if this is the right way to do it.
Also, is there a visualization you would recommend to show 3 variables (income, birth rates, population) by county like this?
Thank you
library(noncensus)
library(zipcode)
library(choroplethr)
library(ggplot2)
library(sp)
library(maps)
#this guy is pretty but needs county names
data(df_pop_county)
county_choropleth(df_pop_county,
title="US 2012 County Population Estimates",
legend="Population",
buckets=1,
zoom=c("new york"))
#this guy has county names
getLabelPoint <- # Returns a county-named list of label points
function(county) {Polygon(county[c('long', 'lat')])#labpt}
df <- map_data('county', 'new york') # NY region county data
centroids <- by(df, df$subregion, getLabelPoint) # Returns list
centroids <- do.call("rbind.data.frame", centroids) # Convert to Data Frame
names(centroids) <- c('long', 'lat') # Appropriate Header
map('county', 'new york')
text(centroids$long, centroids$lat, rownames(centroids), offset=0, cex=0.4)

Related

R cran: sf Sew two MULTILINESTRING/LINESTRING

I try to sew/merge/bind two LINESTRINGs together (spanish coast + french coast) to have the full map of the whole coast. I found all the shpaefiles here:
https://www.marineregions.org/gazetteer.php?p=details&id=3417
https://www.marineregions.org/gazetteer.php?p=details&id=19888
Import and plot the data
frenchCoast_CoteBanyuls <- st_read("coasts_subnational/coasts_subnational.shp") %>%
st_geometry() #
plot(frenchCoast_CoteBanyuls)
spainCoast_CoteBanyuls <- st_read("coasts_subnational SPAIN/coasts_subnational.shp")%>%
st_geometry() #
spainCoast_CoteBanyuls <- st_cast(x = spainCoast_CoteBanyuls, to = "LINESTRING")
plot(spainCoast_CoteBanyuls, add = T)
This map and features seem ok.
According to all the posts I found, I tried to merge the two shapefiles together:
CoteBanyuls_c <- c(frenchCoast_CoteBanyuls, spainCoast_CoteBanyuls)
# CoteBanyuls_rbind <- rbind(frenchCoast_CoteBanyuls, spainCoast_CoteBanyuls)
# CoteBanyuls <- st_union(CoteBanyuls)
# CoteBanyuls <- union(CoteBanyuls)
# CoteBanyuls <- bind(CoteBanyuls)
plot(CoteBanyuls)
the c() function gives a shapefile that does not have the good dimensions (see below) and none of these solutions does plot the good shape of the two coast merged (seems to plot only the spanish coast).
What did I do wrong ? I do not understand why these solutions are not working...
Do you have some ideas ?
Thanks in advance !
Charlotte
I think the issue comes from extracting only the geometry attributes before you combine them. Try this:
frenchCoast_CoteBanyuls <- st_read("coasts_subnational/coasts_subnational.shp")
spainCoast_CoteBanyuls <- st_read("coasts_subnational SPAIN/coasts_subnational.shp")
combined_coast <- rbind(spainCoast_CoteBanyuls, frenchCoast_CoteBanyuls)
mapview::mapview(combined_coast)

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.

R: State and County Outlines for choroplethrZip

I have a dataset with zip codes that I have used choroplethrZip to graph the data. I am looking at the data on the state and county level. However, zip codes don't necessarily correspond with state and county lines. I have tried to use reference_map = TRUE, but it doesn't have county lines, and starts to look a little busy. Is there a way to change the default reference map to one that has state and county lines without the rest of the map detail? In other words, I don't want streets and topography.
Here is my code with the sample data that is similar to the data I am using. You can see the issue with the state of Texas boundaries.
#zip.regions metadata file for choroplethrZip
data(zip.regions)
head(zip.regions)
#Test data file:A data.frame containing population estimates
# for US Zip Code Tabulated Areas (ZCTAs) in 2012.
data(df_pop_zip)
#Create a choropleth of US Zip Codes
zip_choropleth(df_pop_zip,
state_zoom="texas",
title="2012 Texas State ZCTA Population Estimates",
legend="Population",
reference_map = TRUE)
#Zoom County
dd_fips = c(48113, 48121)
zip_choropleth(df_pop_zip,
county_zoom=dd_fips,
title="2012 Denton & Dallas ZCTA Population Estimates",
legend="Population",
reference_map = TRUE)
TexasPlot
DentonDallasPlot
I used this blog and found out how to make this work: http://www.arilamstein.com/blog/2015/07/02/exploring-the-demographics-of-ferguson-missouri/
Here is my final code:
library(choroplethrZip)
library(ggplot2)
library(choroplethr)
#Pull in zip.regions metadata file for choroplethrZip
data(zip.regions)
head(zip.regions)
#Test data file:A data.frame containing population estimates
# for US Zip Code Tabulated Areas (ZCTAs) in 2012.
data(df_pop_zip)
# highlight a county
highlight_county = function(county_fips)
{
library(choroplethrMaps)
data(county.map, package="choroplethrMaps", envir=environment())
df = county.map[county.map$region %in% county_fips, ]
geom_polygon(data=df, aes(long, lat, group = group), color = "yellow", fill = NA, size = 1)
}
#Zoom County
dd_fips = c(48113, 48121)
zip_choropleth(df_pop_zip,
county_zoom=dd_fips,
title="2012 Denton & Dallas ZCTA Population Estimates",
legend="Population",
reference_map = TRUE) +
highlight_county(dd_fips)
Rplot Counties
I just had to add in the highlight_county function and it worked great. When I tested with my data (instead of the generic population data) it worked as well.

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

Making a Choropleth in R without using a gradient

I'm pretty new to R and I am trying to map the distribution of an ant species in Argentina using the adm1 (or state) divisions.
I have downloaded data from the GADM website and I have a csv file that I've created that contains info saying whether the species is present or absent in each adm1.
Even though I don't have a gradient can I still make a choropleth? If not, what other types of maps could I use?
I've looked at several sites including Infomaps using R, How to make choropleths in R, and the Choropleth Map Challenge, which have been really helpful but they all have numeric data and I'm using a present(1) or absent(0) column. The different packages I've tried are sp(with RColorBrewer), ggplot2, rgeos, and maptools.
Here is the code I have so far:
library(sp)
library(RColorBrewer)
write.csv(atr, "atr_data.csv")
atr_data<-read.csv("atr_data.csv", header=TRUE)
spcode country_code adm1_code newcol
1 atr VEN VE.AR 0
2 atr PRY PY.CE 0
3 atr PAN PA.CL 0
4 atr PAN PA.CL 0
5 atr PAN PA.PN 0
6 atr PAN PA.PN 0
I'm in the process of making a column with the full adm1 names instead of the codes so that it will match up with the GADM file (so I haven't written the code to merge the data yet).
#to retrieve map for Argentina ARG
con <- url("http://gadm.org/data/rda/ARG_adm1.RData")
print(load(con))
close(con)
#to generate random colors on map
col = rainbow(length(levels(gadm$NAME_1)))
spplot(gadm, "NAME_1", col.regions=col, main="ARG Regions", colorkey = FALSE, lwd=.4,col="white")
#this piece of code is a mess
col_no <- as.factor(as.numeric(atr_data$newcol[order],
c(0,1)))
levels(col_no)<- c("0", "1")
gadm$col_no <- col_no
myPalette<-brewer.pal(3, "Purples")
spplot(gadm, "col_no", col=grey(.9),
col.regions=myPalette,
main="Distribution of Atratus in Argentina")
Any help would be greatly appreciated, thanks!
There's a couple of minor issues that come up in the example you've provided.
First, the data slot for spatial polygon dataframes can be accessed with gadm#data$col_no instead of gadm$col_no. Once you've finished filling out your presence/absence table, either by accessing the slot directly, or using spCbind in the maptools package allows you to add the presence/absence data to the spatial polygon data frame.
Second, if you have only 2 levels in your col_no factor, you will have to subset MyPalette to 2 colours since the Brewer palette will only work with a minimum of 3 levels.
library(sp)
library(RColorBrewer)
con <- url("http://gadm.org/data/rda/ARG_adm1.RData")
print(load(con))
close(con)
# Randomly assigning presence/absence data for display purposes only
gadm#data$col_no <- as.factor(rbinom(n = 24, size = 1, prob = 0.5))
myPalette <- brewer.pal(3, "Purples")
# col.regions is limited to 2 colors below with the middle color dropped.
spplot(gadm, zcol = "col_no", colorkey = TRUE, col.regions = myPalette[-2],
main="Distribution of Atratus in Argentina")

Resources