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?
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")))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With