I'm trying to do a map using library tmap and this dataset.
Following this discussion, I'm using the following simple code:
library(tmap)
library(geobr)
library(sf)
rg = st_as_sf(polygons_regioes_adm_sp)
tm_shape(rg) +
tm_polygons("regiao_administrativa",
legend.show = F) +
tm_text("regiao_administrativa", size = 1/2)
That yields the following map with overlapping DUPLICATE text. I tried insert remove.overlap = TRUE inside tm_text but this doesn't worked better.
Furthermore i'm getting the following message:
old-style crs object detected; please recreate object with a recent sf::st_crs()
In this context, How I get a map without duplicate text ?
Your code to display the map with the tmap library is fine. The problem is that the sf object polygons_regioes_adm_sp has a mixture of POLYGON and MULTIPOLYGON. So, you just need to simplify the sf object by running the st_cast() function.
As for the projection problem, you just need to specify the EPSG code to assign a recent form of the CRS to the sf object (NB: as for the warning message - cf.below - do not worry, it is fine)
So, please find below the code to display correctly the names of the administrative regions.
library(tmap)
library(sf)
library(dplyr) # please, do not forget to load this library
rg <- polygons_regioes_adm_sp %>%
st_set_crs(4674) %>%
st_cast()
#> old-style crs object detected; please recreate object with a recent sf::st_crs()
#> Warning: st_crs<- : replacing crs does not reproject data; use st_transform for
#> that
tm_shape(rg) +
tm_polygons("regiao_administrativa",
legend.show = F) +
tm_text("regiao_administrativa", size = 1/2)
Created on 2021-11-13 by the reprex package (v2.0.1)
Related
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()
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)
I am trying to make a map with tmap and when I try to view it, this error code comes up:
Error: Fill argument neither colors nor valid variable name(s)
Here is my code.
tm1=tm_shape(myshptime1)+
tm_polygons("zeta.x",style="pretty",
palette="PuOr", title="Spatial Residual \n Relative Risk ")+
tm_layout(frame = FALSE)
tm1
I've tried adding a fill argument, I've tried adding other types of arguments, and I get the same error. I also tried switching from "plot" to "view" to display the map under a different mode and it doesn't work.
This seems to be an issue with your shapefile, which we do not have access to. As your problem is not quite reproducible it will be difficult to help you.
Consider the following example, which uses your exact code but with the shapefile of North Carolina (it ships with the {sf} package, so it is widely available) in place of your myshptime1 object; I have also swapped your "zeta.x" for "AREA", as there is no zeta.x variable in the {sf} shapefile.
library(tmap)
library(sf)
shape <- st_read(system.file("shape/nc.shp", package="sf")) # included with sf package
tm1 = tm_shape(shape)+
tm_polygons("AREA",style="pretty",
palette="PuOr", title="Spatial Residual \n Relative Risk ")+
tm_layout(frame = FALSE)
tm1
Getting error with read_osm from the tmaptools package in R. Want to generate a static map with background layer.
Error is present even when using the example NLD_muni data from tmap package
library(tmap)
library(tmaptools)
library(OpenStreetMap)
tmap_mode("plot")
data(NLD_muni)
test <- tmaptools::read_osm(NLD_muni, type = "esri", zoom = NULL)
Error
Error in FUN(X[[i]], ...) :
Sorry, parameter type `NA' is ambiguous or not supported.
Expected to load a basemap
Could use tmap_mode("view") and created interactive plot but ideally can make a static plot.
I encountered the same problem as you, the examples from the help files don't work anymore for read_osm depending on the help file (this since I upgraded to Windows 10 and reinstalled R - I suspect it is related).
I have found another example on the web which is working for me, and from which you can hopefully start again.
# load Netherlands shape
data(NLD_muni)
# read OSM raster data
osm_NLD <- read_osm(bb(NLD_muni, ext=1.1, projection ="longlat"))
# plot with regular tmap functions
tm_shape(osm_NLD) +
tm_raster() +
tm_shape(NLD_muni) +
tm_polygons("population", convert2density=TRUE, style="kmeans", alpha=.7, palette="Purples")
In order to generate a static base map in tmap using read_osm, the x argument object needs to be in the WGS84 projection (EPSG 4326).
library(tmap)
library(tmaptools)
library(tidyverse)
tmap_mode("plot")
data(NLD_muni)
# This does not work:
NLD_bm <- tmaptools::read_osm(NLD_muni, type = "esri")
# The problem is that NLD_muni is in the projected coordinate system for Netherlands,
# but read_osm wants WGS84
sf::st_crs(NLD_muni) # check the coordinate reference system
# This does work
NLD_bm <- NLD_muni %>%
sf::st_transform(., crs = 4326) %>% # transform NLD_muni to WGS84 projection
sf::st_bbox(.) %>% # extract bounding box of transformed layer
tmaptools::read_osm(., type = "esri") # pass bounding box to read_osm
# Now you can map them
tm_shape(NLD_bm) + tm_rgb() + tm_shape(NLD_muni) + tm_borders(col = "red")
Here is what it looks like:
Two comments:
1) it is not doable to show a basemap with a static {tmap} map; the basemap functionality comes from {leaflet} package, and is therefore available only in view mode.
If you absolutely positively require a basemap in a static map (which is a valid use case) consider using a combination of {ggplot2} and {ggmap}.
2) your loading of NLD_muni is needlesly complex; consider this code instead:
library(tmap)
data(NLD_muni)
tmap_mode("view")
tm_shape(NLD_muni) + tm_polygons(col = "population")
I am having trouble merging shapefiles in R. Here is my code thus far:
library(rgdal)
library(maptools)
library(gridExtra)
setwd("/Users/Cornelius/Dropbox/Cornelius_Sharedfolder")
#Load a geodatabase
fgdb = "/Users/Cornelius/Dropbox/Cornelius_Sharedfolder/RwandaGDB.gdb"
subset(ogrDrivers(), grepl("GDB", name))
fc_list = ogrListLayers(fgdb)
print(fc_list)
#Get the shapefiles from the geodatabase:
Residence=readOGR(dsn=fgdb, layer="RĂ©sidence")
Territoire = readOGR(dsn=fgdb,layer="Territoire")
Chefferie=readOGR(ds=fgdb, layer="Chefferie")
Sous_Chefferie=readOGR(ds=fgdb, layer="Sous_Chefferie")
RwandaPre2002=readOGR(ds=fgdb, layer="RwandaPre2002")
Country_Boundary2012=readOGR(ds=fgdb, layer="Country_Boundary2012")
Province_Boundary2012=readOGR(ds=fgdb, layer="Province_Boundary2012")
Sector_Boundary2012=readOGR(ds=fgdb, layer="Sector_Boundary2012")
District_Boundary2012=readOGR(ds=fgdb, layer="District_Boundary2012")
Cell_Boundary2012=readOGR(ds=fgdb, layer="Cell_Boundary2012")
x = list(Residence, Territoire, Sous_Chefferie, RwandaPre2002, Country_Boundary2012, Province_Boundary2012, Sector_Boundary2012, District_Boundary2012, Cell_Boundary2012)}
This all goes fine. However, when I try to merge two shapefiles - for example, Residence and Territoire, and use the following code, it gives me an error:
test_bind <-spRbind(Territoire, Residence)
The error says: "non-unique polygon IDs."
I'm not sure what this means. Could you please help?