连接分组中的抖动点

huangapple go评论65阅读模式
英文:

Connect jittered points by group

问题

对于这个数据:

set.seed(123)
df <- data.frame(
  ID = 1:50,
  Q = rnorm(50),
  A = rnorm(50, 1)
)

我想连接由ID分组的QA中的成对观察。以下是我目前的代码:

df %>%
  pivot_longer(-ID) %>% 
  ggplot(aes(x = factor(name), y = value, fill = factor(name)))+
  geom_jitter(width = 0.1, alpha = 0.5, col = "blue")+
  geom_line(aes(group = ID),
            alpha = 0.5)

但存在两个问题:

  • (i) 我不确定连接线是否真的是在具有相同ID的观察之间。
  • (ii) 连接线的起点和终点没有抖动,因此它们不总是与点重合。

如何解决这些问题?

英文:

For this data:

set.seed(123)
df &lt;- data.frame(
  ID = 1:50,
  Q = rnorm(50),
  A = rnorm(50,1)
)

I would like to connect the pairwise observations in Q and Agrouped by ID. Here's what I have so far:

df %&gt;%
  pivot_longer(-ID) %&gt;% 
  ggplot(aes(x = factor(name), y = value, fill = factor(name)))+
  geom_jitter(width = 0.1, alpha = 0.5, col = &quot;blue&quot;)+
  geom_line(aes(group = ID),
            alpha = 0.5)

连接分组中的抖动点
But there are two issues:

  • (i) I'm not sure the connecting lines are really between the observations with the same ID
  • (ii) the starting points and end points of the connecting lines are not jittered, therefore they do not always coincide with the dots.

How can these issue be dealt with?

答案1

得分: 2

修复您的问题,为点和线分别明确设置position_jitter,使两者都以相同的幅度进行抖动,并且对于线条切换到geom_path

library(tidyr)
library(ggplot2)

pj <- position_jitter(seed = 1, width = .1, height = 0)

df %>%
  pivot_longer(-ID) %>%
  ggplot(aes(x = factor(name), y = value, fill = factor(name))) +
  geom_point(
    alpha = 0.5, col = "blue",
    position = pj
  ) +
  geom_path(aes(group = ID),
    alpha = 0.5,
    position = pj
  )

连接分组中的抖动点

英文:

To fix your issues set position_jitter explicitly for both the points and the lines so that both are jittered by the same amount and for the lines switch to geom_path:

library(tidyr)
library(ggplot2)

pj &lt;- position_jitter(seed = 1, width = .1, height = 0)

df %&gt;%
  pivot_longer(-ID) %&gt;%
  ggplot(aes(x = factor(name), y = value, fill = factor(name))) +
  geom_point(
    alpha = 0.5, col = &quot;blue&quot;,
    position = pj
  ) +
  geom_path(aes(group = ID),
    alpha = 0.5,
    position = pj
  )

连接分组中的抖动点<!-- -->

huangapple
  • 本文由 发表于 2023年4月4日 16:48:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75927315.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定