ggplot虚线箭头

10
考虑以下轨迹:
test = data.frame(x = c(9500, 25500, 47500), y = c(10.03, 7.81, 0.27))

我想使用ggplot2将此绘制为路径,并用箭头标识方向:

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

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

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

有没有一种方法可以从箭头定义本身中排除 linetype 美学属性?

2
我认为唯一的“解决方案”可能是使用封闭箭头。如果我正确的话,这将是一个不错的问题/PR主题。 - joran
2
哦,看起来这可能已经被整合到grid中了。例如segmentsGrob绘制线和箭头,并且只需要一个gpar参数集。不确定如何在不修复grid的情况下解决此问题。 - joran
1个回答

6
我们可以通过使用具有实线的单独几何图形来解决此问题,绘制箭头头部。就像这样:
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


这对于简单的例子是有效的,但对于一般情况并不实用(例如继承美学或为多条轨迹使用“group”美学)。 - mikeck

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接