Skip to content

Instantly share code, notes, and snippets.

@ar-puuk
Last active May 30, 2025 21:32
Show Gist options
  • Save ar-puuk/c5c9443ac0868321f6e241623a3fab77 to your computer and use it in GitHub Desktop.
Save ar-puuk/c5c9443ac0868321f6e241623a3fab77 to your computer and use it in GitHub Desktop.
# Load necessary libraries
library(sf)
library(tmap)
library(tmaptools)
EU_eflsk_2 <- sf::st_read(
"https://raw.githubusercontent.com/leakyMirror/map-of-europe/refs/heads/master/GeoJSON/europe.geojson"
) |>
sf::st_make_valid()
# Defining the bounding box
bbox <- sf::st_bbox(c(xmin =- 25, ymin =15, xmax=35, ymax=70), crs = sf::st_crs(EU_eflsk_2))
# Cropping the shapefile to the bounding box
EU_eflsk_2_cropped <- sf::st_crop(EU_eflsk_2, bbox)
# Setting tmap to plot mode (static mode)
tmap_mode("plot")
# Creating the map
shapefile_plot <- tm_shape(EU_eflsk_2_cropped) +
tm_borders (col = "black", lwd = 1) + # Add borders
tm_layout (
inner.margins = c(0.1, 0.05, 0.05, 0.05), # Increase bottom margin
outer.margins = c(0.0001, 0.0001, 0.0001, 0.0001), # Small outer margins
frame = TRUE, # Add a frame around the map
frame.lwd = 0.5, # Set frame line width
asp = 0 # Set aspect ratio to automatic
)
# Define the output directory and file path
output_dir <- file.path(proj.path, "project_folder")
plot_file <- file.path(output_dir, "shapefile_plot.png")
# Save the plot as a png file
png(filename= plot_file, width = 1920, height = 1080, res = 300)
# Print plot
print(shapefile_plot)
# Close the graphics device to save the plot
dev.off()
## Alternatively You can view the plot using this:
shapefile_plot
## And export the map using this:
tmap_save(
shapefile_plot,
filename = file.path(proj.path, "project_folder", "shapefile_plot.png"),
width = 1920, height = 1080,
dpi = 300
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment