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

标签 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, .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/

相关文章:

r - geom_boxplot (R) 的股票烛台绘制问题

r - 在ggplot2中循环数据帧

python 情节9: color brewer not enough

charts - 创建类似甘特图的平行条形图,用于并行线程时序可视化

r - 为什么这个 grep 排除在 R 中不起作用?

r - 使用 dplyr mutate 函数替换多个值

r - 插入符号将随机森林建模为 PMML 错误

html - 图中点的CSS样式

r - 如何绘制 ggplot2 散点图的特定颜色和形状?

C#有向图生成库