Created
February 5, 2023 02:03
-
-
Save sarajoha/a7e0639980585996b2e5974d43284338 to your computer and use it in GitHub Desktop.
A simple map using Tmap (R)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# add timeout to successfully intall package | |
# options(timeout = 1200) | |
# install.packages("sf") | |
# libraries used | |
library(sf) | |
library(readxl) # reads xlsx files | |
library(sp) | |
library(tmap) # for static and interactive maps | |
# library(ggplot2) # tidyverse data visualization package | |
path <- "your_path" | |
setwd(path) | |
# readOGR está deprecada, no la uses | |
# country <- readOGR("country_shp", "Country.shp") | |
# ??method the dice que paquetes te faltan | |
# ??readOGR | |
# transform xsls to csv | |
df <- read_excel("hospitals.xlsx") | |
write.csv(df, file = "output/hospitals.csv", row.names = FALSE) | |
df <- read.csv("output/hospitals.csv") | |
# Extract the latitude and longitude values | |
df$latitude <- sapply(strsplit(df$Coordinates, ","), "[[", 1) | |
df$longitude <- sapply(strsplit(df$Coordinates, ","), "[[", 2) | |
# Convert the latitude and longitude values to numeric | |
df$latitude <- as.numeric(df$latitude) | |
df$longitude <- as.numeric(df$longitude) | |
# Convert the data frame into a SpatialPointsDataFrame | |
coordinates <- df[,c("longitude", "latitude")] | |
spdf <- SpatialPointsDataFrame(coordinates, df) | |
# save it as a Geojson | |
spd <- st_as_sf(spdf, coords = c("longitude", "latitude"), crs = 4326) | |
st_write(spd, "output/hospitals.geojson", format = "GeoJSON") | |
# add adminisrative shape | |
boundaries <- st_read("Shapefiles/(...)_adm1_dmmu_20201124.shp") | |
logo <- tmap_icons(file="logo/logo-small.png", keep.asp = TRUE) | |
map_bn = tm_shape(boundaries) + tm_fill(col='purple', alpha=0.2) + tm_borders(col='darkgrey', lwd=2, alpha=0.9) | |
# using the logo as the symbol for the points | |
map_hos = tm_shape(spdf) + tm_symbols(shape=logo, size=0.3, border.col = NULL) | |
# final map | |
map = map_bn + map_hos + tm_layout(title = "Title", fontfamily='Lato', title.size=1.7, bg.color='#F0EBDB') + tm_logo("logo/logo-removebg-preview.png", height=2.5, position=c(0, 0.73)) + tm_logo("logo/other_logo.png", height=2) | |
# save the map | |
tmap_save(map, filename='output/map.png') | |
# cairo_pdf handles fonts better | |
tmap_save(map, filename='output/map.pdf', device=cairo_pdf) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment