Site icon GIS Crack

Maps in R

R is a powerful programming language and environment for statistical computing and graphics. One of its many strengths is the ability to create visualizations, including maps, which help us to explore, understand, and communicate data. R has many packages for working with geospatial data and creating maps, but in this tutorial, we will focus on ggplot2 and sf.

  1. Load the necessary packages: library(ggplot2) and library(sf)

library(ggplot2)
library(sf)

2. Set the location of the data on the computer with setwd

setwd("D:/Documents/MAPASR")

3. Load the data, in this case it will be the provinces of Ecuador in shp format.

provincias_ecuador <- st_read("nxprovincias.shp")

4. Verify that the data has been loaded correctly with str

str(provincias_ecuador)

5. Create a vector of colors called colores that contains 25 colors.

colores <- c("red", "orange", "yellow", "green", "blue", "purple", "pink", "brown", "grey", "black",
"lightblue", "lightgreen", "lightgrey", "darkred", "darkorange", "darkblue", "darkolivegreen",
"hotpink", "indianred", "khaki", "lavender", "lightcoral", "lightpink", "lightyellow", "mistyrose")

6. Create a map with ggplot2 using provincias_ecuador as the data, using the vector of colors to fill the provinces and removing the color guide.

7. Add labels and a title to the map with labs and theme

ggplot(provincias_ecuador) +
geom_sf(aes(fill = DPA_DESPRO), color = "black") +
scale_fill_manual(values = colores, guide = "none") +
labs(x = "Longitud", y = "Latitud", title = "Mapa de las provincias de Ecuador") +
theme(plot.title = element_text(hjust = 0.5))

8. Save the map with ggsave specifying the file name, width, height, and units in centimeters.

ggsave("mapa_provincias_ecuador.png", width = 15, height = 10, units = "cm")

Made with ChatGPT

Exit mobile version