ggplot2: How to add padding/gap to segment end points

Viewed 55
library(ggplot2)

dfr1 <- data.frame(x=c(1,2),y=c(1,2))
dfr2 <- data.frame(x=1,xend=2,y=1,yend=2)

ggplot()+
  geom_point(data=dfr1,aes(x,y),size=6)+
  geom_segment(data=dfr2,aes(x=xend,y=yend,xend=x,yend=y), color="red",arrow = arrow(length=unit(0.10,"cm"), ends="first", type = "closed"))+
  coord_fixed()+
  theme_minimal()

I would like to add some padding/gap to the start and end of the segment so that they do not overlap the points. Here is a manually edited image to show what I mean:

enter image description here

Created on 2022-09-06 by the reprex package (v2.0.1)

Session info
sessioninfo::session_info()
#> ─ Session info ───────────────────────────────────────────────────────────────
#>  version  R version 4.1.0 (2021-05-18)
#>  os       Ubuntu 20.04.5 LTS
#>  system   x86_64, linux-gnu
#> ─ Packages ───────────────────────────────────────────────────────────────────
#>  ggplot2     * 3.3.6   2022-05-03 [1] CRAN (R 4.1.0)
──────────────────────────────────────────────────────────────────────────────
2 Answers

One option would be to use ggh4x::geom_pointpath which

is used to make a scatterplot wherein the points are connected with lines in some order.

and automatically adds some padding which could be specified via the mult argument. However, TBMK it does not allow for different colored points and lines so I added a geom_point on top of it.

library(ggplot2)
library(ggh4x)

dfr1 <- data.frame(x = c(1, 2), y = c(1, 2))

ggplot(dfr1, aes(x, y)) +
  geom_pointpath(
    color = "red", size = 6, mult = .25,
    arrow = arrow(length = unit(0.10, "cm"), ends = "last", type = "closed")
  ) +
  geom_point(size = 6) +
  coord_fixed() +
  theme_minimal()

You could do this manually:

ggplot()+
  geom_point(data=dfr1,aes(x,y),size=6)+
  geom_segment(data=dfr2,
               aes(x = xend - 0.03,
                   y = yend - 0.03,
                   xend = x + 0.03,
                   yend = y + 0.03,), 
               color="red",arrow = arrow(length=unit(0.10,"cm"), ends="first", type = "closed"))+
  coord_fixed()+
  theme_minimal()

enter image description here

Related