R 如何在ggplot2中显示obs的方向(标题)
如何使用ggplot2显示观测的方向(标题)?有没有办法调整R 如何在ggplot2中显示obs的方向(标题),r,ggplot2,visualization,R,Ggplot2,Visualization,如何使用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, .
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
库(ggplot2)
dat我们可以在使用
dplyr
和tidyr::pivot\u wide
:
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")
或者,如果我们希望箭头指向下一个测量值,与颜色无关,我们可以使用下面的代码(由于没有方向,现在只缺少最后一个点):
如果我们想保留“最后一个”测量值,我们可以将它们添加到另一个几何点层中…结合dario的答案,以及
库(dplyr)
图书馆(tidyr)
图书馆(GG2)
dat%>%
枢轴(名称从=时间,值从=c(x,y))%>%
分组依据(id)%>%
突变(x_v=x_2-x_1,y_v=y_2-y_1)%>%
变异于(变量(“x_v”,“y_v”),
列表(单位=~(./sqrt((x_v)^2+(y_v)^2))/1000))%>%
ggplot(aes(x=x_1,y=y_1,颜色=因子(id))+
geom_段(aes(xend=x_1+x_v_单位,yend=y_1+y_v_单位),
show.legend=F,
箭头=箭头(长度=单位(.3,“厘米”),类型=“闭合”,角度=20))+
几何点(数据=(数据%>%过滤器(时间==2)),aes(x,y),形状=15,大小=2)+
实验室(x=“x”,y=“y”,color=“id”)+
主题_bw()
数据:
dat只是澄清一下:你想让每个三角形“指向”x轴上的下一个三角形吗?@John是的,所以obs显示方向。最后一个三角形指向哪里?谢谢。这是一个很好的建议,但我只希望箭头没有线条。我只需要一个时间快照(t=1
),所以我只需要下一个obs。你的箭头解决方案很有效,但我希望我能删除点你是说箭头“角”上画的小点吗?要消除这种情况,只需将系数0.01
替换为0.0001
或超小的值;)我编辑了我的示例以包含该改进@维达,这还不是你想要的答案吗?如果您需要更多定制,我们可以稍微调整箭头。谢谢!不完全是我要找的,但足够近了。干杯
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")
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")