ggplot 带虚线的箭头

mik*_*eck 6 r ggplot2

考虑以下轨迹:

test = data.frame(x = c(9500, 25500, 47500), y = c(10.03, 7.81, 0.27))
Run Code Online (Sandbox Code Playgroud)

我想将此绘制为带有 的路径ggplot2,并带有标识方向的箭头:

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

这看起来不错。但是,如果我想使用虚线,箭头也用虚线绘制,看起来很糟糕:

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

有没有办法linetype从箭头定义本身中排除美学?

dww*_*dww 5

我们可以通过使用具有实线的单独几何图形绘制箭头来解决此问题。像这样的东西:

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")))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明