Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to add arrows to a simple features line in ggplot (geom_sf)

Tags:

r

ggplot2

r-sf

I have a sf layer in R, in real life from a shape file, created externally, but here a super simple line. All I want is to be able to add a arrow head to my lines but geom_sf() doesn't seem to have this capability. Is there any other way around? I want to keep the plot in ggplot as I am just adding one extra layer to existing maps which are set up in ggplot (the actual maps will have several other sf layers with polygons, points and lines). Basically all I want is to add an arrow head like you can in geom_path. Any ideas?

What I have:

library(sf)
library(ggplot2)

line = st_sfc(st_linestring(rbind(c(30,30), c(40,40))), crs = 28355)

ggplot(line)+geom_sf()+coord_sf(datum = 28355)

What I would like, but still using my shapefile data, and proper map projections etc.

dat <- data.frame(x = c(30,40), y = c(30,40))

ggplot(dat, aes(x, y)) + geom_path(arrow = arrow())

Created on 2021-05-06 by the reprex package (v0.3.0)

like image 260
Sarah Avatar asked Sep 01 '25 17:09

Sarah


1 Answers

This is now a feature see reprex:

# --- load packages ----
library(ggplot2)
library(sf)
#> Linking to GEOS 3.9.3, GDAL 3.5.2, PROJ 8.2.1; sf_use_s2() is TRUE

# --- make toy dataframe ----
coords <- data.frame(lat = c(26.562855, 28.538336), 
                     lon = c(-81.949532, -81.379234)) |>
  st_as_sf(coords = c("lon", "lat"),  crs = 4326) |>
  st_coordinates() |>
  st_linestring()

# --- plot ----
ggplot() + 
  geom_sf(data = coords, size = 2, 
          arrow = arrow(angle = 45, 
                        ends = "last", 
                        type = "open", 
                        length = unit(0.5, "cm"))) + 
  theme(
    axis.text.x = element_text(angle = 45, hjust = 1)
  )

Created on 2023-07-29 with reprex v2.0.2

like image 122
Benjamin Hlina Avatar answered Sep 04 '25 07:09

Benjamin Hlina