gpt4 book ai didi

r - 如何在ggplot2中显示obs的方向(标题)

转载 作者:行者123 更新时间:2023-12-03 21:59:01 27 4
gpt4 key购买 nike

如何使用 ggplot2 显示观察的方向(标题)?有没有办法调整shape=17 (三角形)以便它“指向”下一次观察?

示例代码

library(ggplot2)

dat <- data.frame(id = c(1, 1, 2, 2, 3, 3),
time = c(1, 2, 1, 2, 1, 2),
x = c(.1, .2, .3, .4, .5, .6),
y = c(.6, .25, .4, .33, .2, .51))


ggplot(dat, aes(x, y, color=factor(id))) +
geom_point(shape=17) +
# geom_line() +
NULL

enter image description here

最佳答案

我们可以使用 ggplot2::geom_segment 在我们使用 reshape 数据之后dplyrtidyr::pivot_wider :

dat <- data.frame(id = c(1, 1, 2, 2, 3, 3), 
time = c(1, 2, 1, 2, 1, 2),
x = c(.1, .2, .3, .4, .5, .6),
y = c(.6, .25, .4, .33, .2, .51))
library(dplyr)
library(tidyr)
library(ggplot2)
dat %>%
pivot_wider(names_from = time, values_from = c(x, y)) %>%
ggplot(aes(x=x_1, y=y_1, color=factor(id))) +
geom_segment(aes(xend = x_2, yend = y_2),
arrow = arrow(length = unit(.3,"cm"))) +
labs(x="x", y="y", color="id")

ggplot with arrows

编辑:

but I just want the arrow pointing without lines.



我不确定我们应该如何处理每个 id 的第二个点(因为它没有方向)但是如果我们想从图中省略它们,我们可以这样做:
library(dplyr)
library(tidyr)
library(ggplot2)
dat %>%
group_by(id) %>%
arrange(id, time) %>%
mutate(x_2 = x + 0.0001 * (lead(x) - x),
y_2 = y + 0.0001 * (lead(y) - y)) %>%
filter(!is.na(x_2)) %>%
ggplot(aes(x=x, y=y, color=factor(id))) +
geom_segment(aes(xend = x_2, yend = y_2),
arrow = arrow(length = unit(.3,"cm"))) +
labs(x="x", y="y", color="id")

no lines or dots

或者,如果我们希望箭头指向下一个测量值,独立于颜色,我们可以使用下面的代码(由于没有方向,现在只缺少最后一个点):
library(dplyr)
library(tidyr)
library(ggplot2)
dat %>%
arrange(id, time) %>%
mutate(x_2 = x + 0.0001 * (lead(x) - x),
y_2 = y + 0.0001 * (lead(y) - y)) %>%
filter(!is.na(x_2)) %>%
ggplot(aes(x=x, y=y, color=factor(id))) +
geom_segment(aes(xend = x_2, yend = y_2),
arrow = arrow(length = unit(.3,"cm"))) +
labs(x="x", y="y", color="id")

如果我们想保留“最后”的措施 我们可以将它们添加到另一个 geom_point层...

关于r - 如何在ggplot2中显示obs的方向(标题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60674649/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com