【问题标题】:ggplot arrows with dashed lines带有虚线的ggplot箭头
【发布时间】:2018-02-07 04:17:53
【问题描述】:

考虑以下轨迹:

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 美学?

【问题讨论】:

  • 我认为唯一的“解决方案”可能是使用封闭的箭头。对于问题/公关来说将是一个很好的主题(如果我是对的,没有“真正的”方式......)。
  • ...嗯,这似乎可以直接融入 grid 本身。它看起来像,例如segmentsGrob 绘制直线和箭头,并且只接受一组 gpar 参数。不知道如何在 grid 中修复它。

标签: r ggplot2


【解决方案1】:

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

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")))

【讨论】:

  • 这适用于简单示例,但不适用于一般情况(例如,继承美学或对多个轨迹使用group 美学)。
猜你喜欢
  • 2020-04-07
  • 2021-11-06
  • 1970-01-01
  • 2020-05-23
  • 1970-01-01
  • 2021-06-15
  • 1970-01-01
  • 2013-12-14
  • 1970-01-01
相关资源
最近更新 更多