如何使用ggplot2根据线条方向向路径添加多个箭头?

Dan*_* C. 6 r path line direction ggplot2

我有一个数据框,我想从中绘制路径。数据框还指示箭头应具有的方向。我一直在使用这个ggplot2包和geom_path()函数,但是,我想添加指示路径方向的箭头。我使用了该arrow()函数,但我不知道如何按照我想要的方式制作箭头(下面的示例)。

library(ggplot2)

X <- c(0.596, 0.641, 0.695, 0.741, 0.788, 0.837,
       0.887, 0.937, 0.993, 0.984, 0.934, 0.886,
       0.838, 0.778, 0.738, 0.681, 0.642, 0.593)

Y <- c(23.630, 24.085, 24.643, 25.067, 25.491, 25.899,
       26.305, 26.670, 27.049, 27.025, 26.836, 26.636,
       26.429, 26.152, 25.965, 25.664, 25.442, 24.510)

Direction <- c(rep('up', 9), rep('down', 9))

DF <- data.frame(X, Y, Direction)

ggplot(data = DF,
       aes(x = X,
           y = Y)) +
  geom_path(arrow = arrow(ends = "both"))
Run Code Online (Sandbox Code Playgroud)

ggplot2结果

在此输入图像描述

期望的结果

在此输入图像描述

Tje*_*ebo 7

我会将你的路径分成几段并使用 geom_segment。尽管方向将由 geom_segment 中的起点和终点给出,但您仍然需要为两条路径提供一个分组变量,以避免两条路径之间出现难看的箭头。相反,您会看到一个几乎不明显的间隙。但是,如果您不希望出现此间隙,请省略分组步骤 ( group_by)。

您可以按照此流行主题更改箭头的外观。

也许你想看看metR 包,有一个基于向量创建箭头的 geom

library(tidyverse)

X <- c(0.596, 0.641, 0.695, 0.741, 0.788, 0.837, 0.887, 0.937, 0.993, 0.984, 0.934, 0.886, 0.838, 0.778, 0.738, 0.681, 0.642, 0.593)
Y <- c(23.630, 24.085, 24.643, 25.067, 25.491, 25.899, 26.305, 26.670, 27.049, 27.025, 26.836, 26.636, 26.429, 26.152, 25.965, 25.664, 25.442, 24.510)
Direction <- c(rep('up', 9), rep('down', 9))

DF <- data.frame(X, Y, Direction)

DF %>%
group_by(Direction) %>%
mutate(xend = lead(X), yend = lead(Y)) %>%
ggplot( aes(x = X, y = Y)) +
  geom_segment(aes(xend = xend, yend = yend), arrow = arrow())
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


Jak*_*tny 3

你可以试试这个。它根据 中的值分配向上箭头和向下箭头Direction。但它不遵循路径方向。

DF %>%
  ggplot(aes(x = X, y = Y, shape = factor(Direction))) + # converting to factor
  scale_shape_manual(values = c(24, 25)) + # 24 means up arrow and 25 down arrow
  geom_point(size = 2, fill = "black") +
  geom_line() +
  theme(legend.position = "none")
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述