这是一个 ggplot2 解决方案。在这里,我假设当你说你想要“趋势”时,你想为数据拟合一些模型。在这里,我为每个性别拟合了一个线性模型。
我不认为这张图那么好,因为它没有表明相同点是如何ID
连接的。您可以通过多种方式处理此问题,如果您只有几个主题,则可以映射shape
到,或者将它们连接并映射到.ID
geom_path
group
ID
library(ggplot2)
df <- read.table(
text = "
ID DEPRESSION TIME GENDER
1 5 1 MALE
1 5 2 MALE
1 4 3 MALE
2 3 1 MALE
2 6 2 MALE
2 8 3 MALE
3 2 1 FEMALE
3 2 2 FEMALE
3 2 3 FEMALE
",
header = TRUE
)
ggplot(df, aes(x = TIME, y = DEPRESSION, color = GENDER)) +
geom_point() +
stat_smooth(method = "lm", se = FALSE)
对于平均线,您必须将每组的平均数预先计算到一个新的数据框中。在这里,我使用dplyr
'sgroup_by
并summarise
为此,给我df_summarised
. geom_hline
然后我只能通过修改data
参数来为图层使用新的数据框。
library(ggplot2)
library(dplyr)
df <- read.table(
text = "
ID DEPRESSION TIME GENDER
1 5 1 MALE
1 5 2 MALE
1 4 3 MALE
2 3 1 MALE
2 6 2 MALE
2 8 3 MALE
3 2 1 FEMALE
3 2 2 FEMALE
3 2 3 FEMALE
",
header = TRUE
)
df_summarised <- df %>%
group_by(GENDER) %>%
summarise(MEAN_DEPRESSION = mean(DEPRESSION))
ggplot(df) +
geom_point(aes(x = TIME, y = DEPRESSION, color = GENDER) +
geom_hline(aes(yintercept = MEAN_DEPRESSION, color= GENDER), data = df_summarised)