英文:
Connect jittered points by group
问题
对于这个数据:
set.seed(123)
df <- data.frame(
ID = 1:50,
Q = rnorm(50),
A = rnorm(50, 1)
)
我想连接由ID
分组的Q
和A
中的成对观察。以下是我目前的代码:
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 <- data.frame(
ID = 1:50,
Q = rnorm(50),
A = rnorm(50,1)
)
I would like to connect the pairwise observations in Q
and A
grouped by ID
. Here's what I have so far:
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) 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 <- 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
)
<!-- -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论