library(ggrepel)
## 载入需要的程辑包:ggplot2
#############Always (or never) draw line segments
#Use min.segment.length = 0 to draw all line segments, no matter how short they are.
#Use min.segment.length = Inf to never draw any line segments, no matter how long they are.
set.seed(42)
dat2 <- subset(mtcars, wt > 3 & wt < 4)
# Hide all of the text labels.
dat2$car <- row.names(dat2)
dat2 <- dat2[1:5, ]
dat2
##                    mpg cyl  disp  hp drat    wt  qsec vs am gear carb
## Hornet 4 Drive    21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
## Hornet Sportabout 18.7   8 360.0 175 3.15 3.440 17.02  0  0    3    2
## Valiant           18.1   6 225.0 105 2.76 3.460 20.22  1  0    3    1
## Duster 360        14.3   8 360.0 245 3.21 3.570 15.84  0  0    3    4
## Merc 240D         24.4   4 146.7  62 3.69 3.190 20.00  1  0    4    2
##                                 car
## Hornet 4 Drive       Hornet 4 Drive
## Hornet Sportabout Hornet Sportabout
## Valiant                     Valiant
## Duster 360               Duster 360
## Merc 240D                 Merc 240D
p <- ggplot(dat2, aes(wt, mpg, label = car)) +
  geom_point(color = "red")
p1 <- p +
  geom_text_repel(min.segment.length = 0, seed = 42, box.padding = 0.5) +
  labs(title = "min.segment.length = 0")
p2 <- p +
  geom_text_repel(min.segment.length = Inf, seed = 42, box.padding = 0.5) +
  labs(title = "min.segment.length = Inf")
gridExtra::grid.arrange(p1, p2, ncol = 2)

##########################Make curved line segments or arrows
#The line segments can be curved as in geom_curve() from ggplot2.
#segment.curvature = 1 increases right-hand curvature, negative values would increase left-hand curvature, 0 makes straight lines
#segment.ncp = 3 gives 3 control points for the curve
#segment.angle = 20 skews the curve towards the start, values greater than 90 would skew toward the end
ggplot(dat2, aes(wt, mpg, label = car)) +
  geom_point(color = "red") +
  geom_text_repel(
    nudge_x = .1, #Horizontal and vertical adjustments to nudge the starting position of each text label. 
    box.padding = 1, #Amount of padding around bounding box, as unit or number.
    nudge_y = 0.6,
    segment.curvature = -0.5,
    segment.ncp = 2,
    direction  = "x",
    hjust             = 0,
    segment.size      = 1,
    segment.angle = 15,
    segment.square    = FALSE,
    segment.inflect   = TRUE,
    force_pull   = 0, # do not pull toward data points
    max.iter = Inf,
    segment.color = "blue",
    color = "skyblue",     # text color
    bg.color = "grey30", # shadow color
    bg.r = 0.15          # shadow radius
    )

#ref https://ggrepel.slowkow.com/articles/examples.html