Skip to main content

Drawing parallel coast lines off Peru

R
tutorial
How to draw parallel coast lines off Peruvian coast using R | Cómo dibujar líneas paralelas a la costa peruana con R
Published

September 23, 2026

Keywords

parallel coastlines, R, sf, Shiny, tutorial

Image credits: Global Ocean Physics Analysis and Forecast. E.U. Copernicus Marine Service Information (CMEMS). Marine Data Store (MDS). DOI: https://doi.org/10.48670/moi-00016 (Accessed on 31 08 2026)

[EN] Generating Lines Parallel to the Peruvian Coast

Method 1: Shiny App

If we only need parallel lines at specific integer nautical mile distances, we can use a Shiny app I developed, which is available at:

https://01a0b12b-4a16-f145-4617-420ede0a160b.share.connect.posit.cloud/

This Shiny application allows users to interactively visualize different buffers or distance lines from the Peruvian coastline, for distances ranging from 1 to 300 nautical miles. Users can select multiple distances, view the results on OpenStreetMap, topographic, or satellite basemaps, and download the selected geometries in GeoPackage format for use in other geospatial analysis projects. The source code for this Shiny app is available in the repository https://github.com/LuisLauM/peruvian_buffers.

How to Use

The controls are quite straightforward:

  • A text input field where users can enter any INTEGER values between 1 and 300, separated by commas. These values will be used to generate the corresponding parallel lines.

  • A selector that lets you choose whether to display lines or polygons.

  • A dropdown menu where users can choose from three basemap visualization options.

  • A button to download the selected parallel lines as a GeoPackage file.

What to Do Next?

The Shiny app allows users to download a file in GeoPackage format. This type of file can subsequently be read by multiple platforms, including ArcGIS, QGIS, Python, and, of course, R.

Below, I provide an example of the commands required to read this type of file:

require(sf)

parallels <- st_read(
  dsn = "buffers_costa_50_100_150_200_300.gpkg", 
  layer = "buffers_costa",
  quiet = TRUE
)

parallels
Simple feature collection with 5 features and 2 fields
Geometry type: MULTILINESTRING
Dimension:     XY
Bounding box:  xmin: -86.33183 ymin: -34.8773 xmax: -70.92157 ymax: 9.571371
Geodetic CRS:  WGS 84
  featurecla distancia_mn                           geom
1       Land           50 MULTILINESTRING ((-82.15091...
2       Land          100 MULTILINESTRING ((-82.98591...
3       Land          150 MULTILINESTRING ((-83.82081...
4       Land          200 MULTILINESTRING ((-84.6557 ...
5       Land          300 MULTILINESTRING ((-86.30878...

To plot the lines from the loaded object, we can use:

  • Base R graphics:
plot(x = parallels[,2])

  • ggplot2 environment:
require(ggplot2)

ggplot() +
  
  geom_sf(
    mapping = aes(
      color = as.factor(distancia_mn)
    ),
    data = parallels
  ) +
  
  theme_minimal() +
  
  labs(color = "Distance (mn)")

Method 2

What if I need to generate parallel lines at an exact distance from the coastline (not necessarily an integer number of nautical miles)? One option is to use the buffer-generation script from the Shiny app, available in my repository, and modify the predefined values in the bufferDistances_nm vector: link.

Another option is to use the peruvian_buffers function, available in my ruisu package. The simplest call only requires defining a numeric vector of distances:

# Install ruisu from Github (run just once)
# remotes::install_github("LuisLauM/ruisu")

require(ruisu)

peruvian_buffers(distances = c(50, 200, 150, 200, 300))

However, peruvian_buffers also allows users to modify the units (the units argument) and the reference coastline section used to generate the buffers (the subset_limits argument).

peruvian_buffers(
  distances = c(100, 150, 150, 200, 300),
  units = "km", 
  subset_limits = list(
    x = c(-150, -70), 
    y = c(-30, 5)
  )
)

The returned object is a list of sf objects.

This function is very recent and is therefore likely to undergo further improvements or corrections. If you encounter any issues or have suggestions for improvement, please submit them through a GitHub Issue: link


[ES] Generar líneas paralelas a la costa peruana

Método 1: app de Shiny

Si solo necesitamos las líneas paralelas para cierto valor entero en millas náuticas, podemos utilizar un app Shiny que desarrollé y que está disponible en:

https://01a0b12b-4a16-f145-4617-420ede0a160b.share.connect.posit.cloud/

Esta aplicación Shiny permite visualizar de forma interactiva distintos buffers o líneas de distancia respecto a la costa del Perú, para valores entre 1 y 300 millas náuticas. El usuario puede seleccionar varias distancias, consultar los resultados sobre mapas base de OpenStreetMap, topográficos o satelitales, y descargar las geometrías elegidas en formato GeoPackage para utilizarlas en otros proyectos de análisis geoespacial. El código de este Shiny se halla disponible en el repositorio https://github.com/LuisLauM/peruvian_buffers.

Modo de uso

Los controles son bastante simples:

  • Un campo de texto en donde el usuario puede colocar cualquier valor ENTERO entre 1 y 300 separado por comas. Estos valores serán utilizados para dibujar las líneas paralelas correspondiente.

  • Un selector que permite definir si desea obtener Líneas o Polígonos.

  • Un campo desplegable en donde el usuario puede elegir entre tres opciones de visualización para el mapa de fondo.

  • Un botón para descargar las paralelas elegidas a modo de un archivo en formato GeoPackage.

¿Qué hacer luego?

El app de Shiny permite descargar un archivo en formato GeoPackage. Este tipo de archivos puede ser leído posteriormente en múltiples plataformas: ArcGis, QGIS, Python y, por supuesto, en R.

A continuación, presento un ejemplo de los comandos necesarios para leer un archivo de este tipo:

require(sf)

paralelas <- st_read(
  dsn = "buffers_costa_50_100_150_200_300.gpkg", 
  layer = "buffers_costa",
  quiet = TRUE
)

paralelas
Simple feature collection with 5 features and 2 fields
Geometry type: MULTILINESTRING
Dimension:     XY
Bounding box:  xmin: -86.33183 ymin: -34.8773 xmax: -70.92157 ymax: 9.571371
Geodetic CRS:  WGS 84
  featurecla distancia_mn                           geom
1       Land           50 MULTILINESTRING ((-82.15091...
2       Land          100 MULTILINESTRING ((-82.98591...
3       Land          150 MULTILINESTRING ((-83.82081...
4       Land          200 MULTILINESTRING ((-84.6557 ...
5       Land          300 MULTILINESTRING ((-86.30878...

Para graficar las líneas del objeto cargado, podemos hacerlo a través de:

  • Entorno graphics:
plot(x = paralelas[,2])

  • Entorno ggplot2:
require(ggplot2)

ggplot() +
  
  geom_sf(
    mapping = aes(
      color = as.factor(distancia_mn)
    ),
    data = paralelas
  ) +
  
  theme_minimal() +
  
  labs(color = "Distancia (mn)")

Método 2

¿Y qué puedo hacer si necesito dibujar paralelas con un valor de distancia a la costa exacto (no entero en millas náuticas). Una opción puede ser utilizar el script generador de buffers del app Shiny, disponible en mi repositorio, y cambiar los valores predefinidos en el vector bufferDistances_nm: link.

Otra opción también es utilizar la funcíon peruvian_buffers, disponible dentro de mi paquete ruisu. El comando más sencilo requiere solo definir un vector numérico para las distancias:

# Instalar ruisu desde Github (ejecutar solo una vez)
# remotes::install_github("LuisLauM/ruisu")

require(ruisu)

peruvian_buffers(distances = c(50, 200, 150, 200, 300))

Sin embargo, peruvian_buffers permite también modificar las unidades (argumento units) y la sección de línea de costa de referencia para dibujar los buffers (argumento subset_limits).

peruvian_buffers(
  distances = c(100, 150, 150, 200, 300),
  units = "km", 
  subset_limits = list(
    x = c(-150, -70), 
    y = c(-30, 5)
  )
)

El objeto retornado será una lista de objetos sf.

Esta función es muy reciente, por lo que es muy susceptible a mejoras o correcciones. Para cualquiera de esos casos, por favor, hazlo a través de un Issue en Github: link