Global cartogram in R - r

I am trying to create a global cartogram using the cartogram package in R. I am trying to use the data from wrld_simpl. What I expect is a cartogram in which the Population ("Pop2005" variable) is plotted. The code I have developed is this:
data(wrld_simpl)
world<-wrld_simpl
world_sf = st_as_sf(world)
world_sf_proj = st_transform(world_sf, crs = 3785)
world_cartogram <- cartogram_cont(world_sf_proj, "POP2005")
plot(world_cartogram)
Nonetheless, this has resulted in the following figure:
Do you know what is wrong with the code? Maybe the CRS? I have tried to use others CRS but I got the following error:
"Error: Using an unprojected map. This function does not give correct centroids and distances for longitude/latitude data:
Use "st_transform()" to transform coordinates to another projection."

Taken from this documentation, it is stated that
The default plot of an sf object is a multi-plot of all attributes, up
to a reasonable maximum
If you want to use the base R plot function, then use st_geometry(your_map) to plot (the geometry) an sf object.
Another possibility (which I don't recommend) is to set plot options to 1 plot maximum (options(sf_max.plot=1)), but this plots the first variable, and it might not be the best idea.
library(sf)
library(spData)
library(cartogram)
library(tidyverse)
world_sf = st_as_sf(world)
world_sf_proj = st_transform(world_sf, crs = 3785)
world_cartogram <- cartogram_cont(world_sf_proj, "pop")
plot(st_geometry(world_cartogram))
Now, sf is particularly well suited with ggplot2 and the tidyverse. In that setting, just use ggplot in combination with geom_sf.
ggplot(world_cartogram) +
geom_sf()

Related

ggplot2 overwrites plot limits

I have two shapefiles, which I would like to plot into a given plot extent. One of the shapefiles exceeds the extent and when plotted it automatically overwrites the limits of the extent. This happens when loading the shapefiles using the terra package and plotting it using the tidyterra functions, but it is not an issue when reading the shapefiles using the old readOGR function and ploting it using the core ggplot2 functions.
# libraries
library(terra)
library(tidyterra)
library(ggplot2)
library(ggspatial)
library(raster)
library(sp)
library(sf)
library(rgdal)
EXAMPLE 1 - I don't want this
# read shapefiles
SHP1 <- terra::vect('file1.shp')
SHP2 <- terra::vect('file2.shp')
# plot
ggplot() +
coord_equal(ylim=c(100000,800000)) +
geom_spatvector(data=SHP1,fill=NA,color='grey',inherit.aes=T) +
geom_spatvector(data=SHP2,fill=NA,color='green',size=1)
EXAMPLE 2 - I want this
# read shapefiles
SHP1 <- terra::vect('file1.shp')
SHP2 <- terra::vect('file2.shp')
ggplot() +
coord_equal(ylim=c(100000,800000)) +
geom_polygon(SHP1,mapping=aes(x=long,y=lat,group=group),fill=NA,color='grey',size=0.1) +
geom_polygon(SHP2,mapping=aes(x=long,y=lat,group=group),fill=NA,color='green',size=0.5)
How could I obtain map from example 2 using the geom_spatvector function used in example 1?
I really would like to use the terra package to read and manipulate shapefiles but then it produces SpatVector class object which is not supperted by the ggplot2 function. This means that only for the plotting purposes I have to transfer it to the older SpatialPolygonsDataFrame and this is exactly what I would like to avoid.
You need to use coord_sf rather than coord_equal. Obviously, we don't have your shapefile, but if I take a similar shapefile of Germany, then we can demonstrate:
library(tidyterra)
library(ggplot2)
p <- ggplot(SHP1) +
geom_spatvector()
Firstly, with the standard geom_spatvector plot:
p
Secondly, with axis limits written by a call to geom_sf:
p + coord_sf(ylim = c(47, 52))

Represent a colored polygon in ggplot2

I am using the statspat package because I am working on spatial patterns.
I would like to do in ggplot and with colors instead of numbers (because it is not too readable),
the following graph, produced with the plot.quadratest function: Polygone
The numbers that interest me for the intensity of the colors are those at the bottom of each box.
The test object contains the following data:
Test object
I have looked at the help of the function, as well as the code of the function but I still cannot manage it.
Ideally I would like my final figure to look like this (maybe not with the same colors haha):
Final object
Thanks in advance for your help.
Please provide a reproducible example in the future.
The package reprex may be very helpful.
To use ggplot2 for this my best bet would be to convert
spatstat objects to sf and do the plotting that way,
but it may take some time. If you are willing to use base
graphics and spatstat you could do something like:
library(spatstat)
# Data (using a built-in dataset):
X <- unmark(chorley)
plot(X, main = "")
# Test:
test <- quadrat.test(X, nx = 4)
# Default plot:
plot(test, main = "")
# Extract the the `quadratcount` object (regions with observed counts):
counts <- attr(test, "quadratcount")
# Convert to `tess` (raw regions with no numbers)
regions <- as.tess(counts)
# Add residuals as marks to the tessellation:
marks(regions) <- test$residuals
# Plot regions with marks as colors:
plot(regions, do.col = TRUE, main = "")

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)

r geom_map fails with GeoJSON map simplified with gSimplify

I'm constructing world maps with countries color-filled with the (continuous) value depending on a column in a data frame called temp.sp. I want to put several of these maps in a graph. I construct each map using ggplot with geom_map and then construct and display the graphs using multiplot() which uses grid code.
I'm using a GeoJSON map (world <- readOGR(dsn = "ne_50m_admin_0_countries.geojson", layer = "OGRGeoJSON")). The resulting SpatialPolygonsDataFrame is 4.1 Mb and the dataframe that results from worldMap <- broom::tidy(world, region = "iso_a3") has 93391 rows. So when I run multiplot with 4 plot files, it takes a long time.
I thought that I could speed up the printing by simplifying the world map with gSimplify using code like world.simp <- gSimplify(world, tol = .1, topologyPreserve = TRUE). The resulting data frame, worldMap.simp only has 27033 rows but when I use this map I get the error message Error in unit(x, default.units) : 'x' and 'units' must have length > 0.
The error message is generated when I run this code with worldMap.simp. When I use worldMap I have no problems.
gg <- ggplot(temp.sp, aes(map_id = id))
gg <- gg + geom_map(aes(fill = temp.sp$value), map = worldMap.simp, color = "white").
I tried converting temp.sp$value to factor but it made no difference.
To summarize, using a gSimplified map causes the displaying of a graph produced with ggplot and geom_map to fail.
Rather than try to figure out what was going wrong with gSimplify, I found and downloaded a lower resolution map from http://geojson.xyz. The one I'm currently using is
https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_110m_admin_0_countries.geojson
Note that it has a similar filename, but with 110m instead of 50m.

Using a raster attribute from a multi-attribute raster for colour levels in a plot in R

I have a raster object with a large number of attributes, and I would like to plot the spatial data in R and colour code it by a certain attribute. I have not been able to work out how to use the information of a particular attribute to achieve this. So far I have successfully extracted the attribute of choice using factorValues(), but I cannot determine how to now incorporate this information into the plot() function. I tried using the ratify() and level() functions mentioned in the raster package documentation, but I don’t understand how the simplified online examples can be adapted for a raster with multiple attributes.
Any advice on how to achieve this would be greatly appreciated.
# read in shapefile
shp = readOGR(".", "grid")
#convert to raster
r = raster(extent(shp))
res(r) = c(1,0.5)
ra = rasterize(shp, r)
#crop raster to desired extent
rcrop = crop(ra, extent(-12, 2, 29, 51))
# extract attribute value of interest
f = factorValues(rcrop, 1:420, layer=1, att=17, append.names=FALSE)
# here there are 420 cells in the raster and I am interested in plotting values of attribute 17 of the raster (this is currently a numeric attribute, not a factor)
#extra code to set attribute as the level to use for plotting colours???
rcrop = ratify(rcrop)
rat = levels(rcrop)[[1]] #this just extras row IDs..not what I want
#…
### plot: I want to plot the grid using 7 colours (I would ideally like to specify the breaks myself)
require(RColorBrewer)
cols = brewer.pal(7,"YlGnBu")
#set breaks
brks = seq(min(minValue(rcrop)),max(maxValue(rcrop),7))
#plot
plot(rcrop, breaks=brks, col=cols, axis.arg=arg)
The following is pretty hacky (and may perform poorly for large rasters), but I'm not sure if there's a way to link col.regions to a specified attribute.
rasterVis::levelplot does a nice job of labelling colour ramps corresponding to factor rasters, and while it provides an att argument allowing you to specify which attribute you're interested in, this seems to only modify the labelling of the ramp. Raster cell values control how the colour ramp is mapped to the raster, so it seems to me that we need to modify the cell values themselves. Maybe #OscarPerpiñán will chime in here to prove me wrong :)
We can create a simple function to substitute the original cell values with whichever attribute we want:
switch_att <- function(r, att) {
r[] <- levels(r)[[1]][values(r), att]
r
}
Let's download and import a small example polygon dataset from Natural Earth:
library(rasterVis)
library(rgdal)
require(RColorBrewer)
download.file(file.path('http://www.naturalearthdata.com',
'http//www.naturalearthdata.com/download/110m/cultural',
'ne_110m_admin_0_countries.zip'),
f <- tempfile())
unzip(f, exdir=tempdir())
shp <- readOGR(tempdir(), 'ne_110m_admin_0_countries')
rasterize the vector data:
r <- rasterize(shp, raster(raster(extent(shp), res=c(1, 1))))
And create some plots with levelplot:
levelplot(switch_att(r, 'continent'), col.regions=brewer.pal(8, 'Set2')) +
layer(sp.polygons(shp, lwd=0.5))
levelplot(switch_att(r, 'economy'), par.settings=BuRdTheme) +
layer(sp.polygons(shp, lwd=0.5))
EDIT
With Oscar's update to rasterVis, the switch_att hack above is no longer necessary.
devtools::install_github('oscarperpinan/rastervis')
levelplot(r, att='continent', col.regions=brewer.pal(8, 'Set2')) +
layer(sp.polygons(shp, lwd=0.5))
will produce the same figure as the first one above.

Resources