[英]How to plot the average time series of multiple individuals
I have time series data where measurements of 7 variables ( Var1:Var7
) were taken on 15 individuals (denoted by a unique ID
).我有时间序列数据,其中对 15 个个体(由唯一ID
表示)进行了 7 个变量 ( Var1:Var7
) 的测量。 These individuals were sampled from 3 different Location
s.这些个体是从 3 个不同的Location
采样的。 Note that the number of observations is different for each individual.请注意,每个人的观察次数不同。 I believe the individuals within each Location
will be more similar to each other than individuals in other Location
s, both in value and trend.我相信每个Location
个体在价值和趋势上都会比其他Location
的个体更相似。 For each Variable
within each Location
, I want to plot the average time series (to get an idea of what the group looks like as a whole) up to the point where Time
is the same for each individual (so the length of the x-axis will only be as long as the shortest individual).对于每个Location
每个Variable
,我想绘制平均时间序列(以了解该组作为一个整体的样子)直到每个人的Time
相同(因此 x-轴将只与最短的个体一样长)。 How can I do this and add error bars for each Time
point to see how much variation exists between individuals?我怎样才能做到这一点并为每个Time
点添加误差线以查看个体之间存在多少差异? Here is some sample data:以下是一些示例数据:
set.seed(123)
ID = factor(letters[seq(15)])
Time = c(1000,1200,1234,980,1300,1020,1180,1908,1303,
1045,1373,1111,1097,1167,1423)
df <- data.frame(ID = rep(ID, Time), Time = sequence(Time))
df$Location = rep(c("NY","WA","MA"), c(5714,7829,4798))
df[paste0('Var', c(1:7))] <- rnorm(sum(Time))
The values of all your variables are the same, so I did the following to make it more random:所有变量的值都相同,因此我执行了以下操作以使其更加随机:
for(i in 1:7) df[paste0('Var', i)] <- rnorm(sum(Time))
Then the following code gives a time-series plot for each of the 7 variables averaged over the three locations.然后下面的代码给出了三个位置平均的 7 个变量中的每一个的时间序列图。
df %>%
pivot_longer(cols = Var1:Var7, names_to="Variable") %>%
group_by(Location, Variable, Time) %>%
summarise(mval=mean(value)) %>%
ggplot(aes(y=mval, x=Time, color=Variable)) +
geom_line() +
facet_grid(~Location) # , scales="free" # ?
I'm not sure if this is what you had in mind though.我不确定这是否是你的想法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.