Skip to content
Prev 398041 / 398502 Next

ggplot with arrows

On 8/1/2025 3:43 PM, Ebert,Timothy Aaron wrote:
Hello,

First of all, according to the documentation ?stat_function, section 
Arguments,


data	
Ignored by stat_function(), do not use.


As for the arrows, first get the equations of the lines tangent to the 
end points of the parabola,

y = -10*x - 25
y = 10*x - 25

then compute segments' end points and plot.


f <- function(x, b = -25, m) m*x + b
arrow_data <- data.frame(
   id = c("n", "p"),
   x = c(-5, 5),
   y = f(c(-5, 5), m = c(-10, 10)),
   xend = c(-6, 6),
   yend = f(c(-6, 6), m = c(-10, 10))
)

ggplot() +
   stat_function(
     fun = function(x) x^2,
     color = "blue", linewidth = 1.25,
     xlim = c(-5, 5)
   ) +
   geom_segment(
     data = arrow_data,
     mapping = aes(x = x, y = y, xend = xend, yend = yend, group = id),
     arrow = arrow(length = unit(0.5, "cm")),
     linewidth = 1.25,
     linetype = "dashed",
     inherit.aes = FALSE
   ) +
   theme_linedraw()



Remove linetype and add color if you want.

Hope this helps,

Rui Barradas