Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot arrows with dashed lines

Tags:

r

ggplot2

Consider the following trajectory:

test = data.frame(x = c(9500, 25500, 47500), y = c(10.03, 7.81, 0.27))

I want to plot this as a path with ggplot2, with an arrow identifying the direction:

ggplot(test) + aes(x = x, y = y) +
  geom_path(size = 1, 
    arrow = arrow(type = "open", angle = 30, length = unit(0.1, "inches")))

This looks fine. However, if I want to use a dashed line, the arrow is also drawn with a dashed line, which looks terrible:

ggplot(test) + aes(x = x, y = y) +
  geom_path(linetype ="dashed", size = 1, 
    arrow = arrow(type = "open", angle = 30, length = unit(0.1, "inches")))

Is there a way to exclude the linetype aesthetic from the arrow definition itself?

like image 442
mikeck Avatar asked Feb 06 '18 19:02

mikeck


1 Answers

We can work around the issue by drawing the arrow head with a separate geometry that has a solid line. Something like this:

geom_end_arrow = function(path, arrow, ...) {
  path = tail(path,2)
  x.len = diff(path$x)/1000
  y.len = diff(path$y)/1000
  path$x[1] = path$x[2] - x.len
  path$y[1] = path$y[2] - y.len
  geom_path(data = path, mapping = aes(x=x, y=y), arrow=arrow, ...)
}

ggplot(test) + aes(x = x, y = y) +
  geom_path(linetype ="dashed", size = 1) +
  geom_end_arrow(test, size = 1, arrow = arrow(type = "open", angle = 30, length = unit(0.1, "inches")))

enter image description here

like image 55
dww Avatar answered Sep 21 '22 08:09

dww