Time series visualization

Packages: dplyr, tidyr, ggplot2, ggExtra


In this section, we introduce the basics of time series plotting. It is used as a base for other advanced time series plots that can be found on this website.

This approach serves multiple purposes. Firstly, it offers a descriptive perspective, providing a comprehensive understanding of the temporal patterns within the data. Secondly, plotting the time series aids in uncovering both within- and between-participant, or dyad differences and patterns (e.g., trends, seasonality) as well as exploring relationships between variables. Such nuanced information may be challenging to identify without the aid of visual plots. Hence, it is a tool to facilitate hypothesis generation through observational analysis, allowing researchers to generate pertinent questions and hypotheses for future studies. Additionally, these plots continue to serve as a valuable tool for identifying any potential issues (e.g., outliers) that may arise in subsequent analyses. Lastly, it is an effective means of communicating research findings.

Participants and dyads

A straightforward and basic way to plot a time series in ESM studies is by representing the values reported by a single participant against the corresponding beep numbers on the x-axis. This type of plot effectively illustrates the temporal progression of the participant’s responses throughout the study. We can use an R base function: ‘plot.ts()’.

data_pp = data[data$id==12,]  # Select a participant 
plot.ts(data_pp$PA1)

In order to improve the interpretation of time series plots, we would like to highlight two aspects of the above plots First, it is important to consider the scale of the axes, both to understand the process but also when comparing time series plots. In the above plots, the range is restricted to the actual values taken by the time series. Hence, it is convenient to fix it so the y-axis will cover the actual range (e.g., 1-100). Second, some functions or users remove missing values while plotting. Hence, time points are all linked together with no gaps to represent actual missing values, which in return leads to a wrong impression of completeness and an overestimation of the quality of the data. On the other hand, isolated valid observations (no response to the previous and following beeps) can vanish (see the first plot) whenever only using lines aesthetics. It is a good practice to always add points (with ‘geom_point’) to make sure they are included in the plot. Another improvement is to make sure that line is displayed between observations that have regular time intervals. For instance, we can choose to only link observations that are from the same day. We propose 2 methods:

  1. A time series with ‘geom_line()’ and ‘geom_point()’ from the ggplot2 package.
  2. Identical, but we restrict the lines for observations within the same day. To do so we can use ‘as.Date(sent)’ or the day number variable as a grouping variable.

data_pp = data[data$id==12,]  # Select a participant 
data_pp %>% 
    ggplot(aes(x=obsno, y=PA1)) +
        geom_line() +
        geom_point() +
        coord_cartesian(ylim=c(0,100))

Building on the previous plots, we can now display multiple participants/variables in one plot. Whenever the dataset contains multiple participants/variables, we might first need to select a subset of the data. We present different possibilities. First, we can split variables and participants in different subplots using the ‘facet_grid()’ (or ‘facet_wrap()’) function:

  1. One participant over multiple variables
  2. Multiple participants over one variable
  3. Multiple participants over multiple variables

data_pp = data[data$id==12,]  # Select a participant 
data_pp %>% 
  gather(var, val, PA1:PA3) %>%
  ggplot(aes(x=obsno, y=val, color=var)) +
    geom_line() +
    geom_point() +
    facet_grid(var~.)

Another solution is to merge the multiple variables of a participant in one plot. Color is then used to differentiate variables. Hence, we can plot:

  1. One participant over multiple variables
  2. Multiple participants over multiple variables

data_pp = data[data$id==12,]  # Select a participant 
data_pp %>% 
  gather(var, val, PA1:PA3) %>%
  ggplot(aes(x=obsno, y=val, color=var)) +
    geom_line() +
    geom_point()

Finally, rather than choosing participants as grouping variables, we can choose to group by dyads. It is particularly useful to have a direct comparison of the partners’ time series. For instance, for one or three variables, we plot multiple dyads with both partners distinguished by the ‘role’ variable (e.g., parent/child, woman/man):

data %>% 
  filter(dyad %in% c(6,9,17,26)) %>%    # Select a subset of participant
  ggplot(aes(x=obsno, y=PA1, color=factor(role))) +
    geom_line() +
    geom_point() +
    facet_grid(dyad~.)

Continuous time axis

Utilizing the beep number may not accurately reflect the actual time duration between successive beeps, resulting in an inaccurate representation of the temporal dynamics. This can be particularly misleading when analyzing and interpreting time-dependent patterns, as the variation in time intervals may distort the true temporal relationships between data points. Therefore, using a continuous time scale can be essential for maintaining the integrity and accuracy of the temporal information in time series analysis.

The first step is then to compute a continuous time variable. You can look back to the create time variables section for further information. Below we take one hour as the unit (60 minutes) and the start of the continuous time scale is the first day (at midnight) of response for each participant.

unit = 60 # in minutes

data = data %>% 
  group_by(id) %>%
  mutate(start_pp = as.Date(min(start, na.rm=TRUE))) %>% 
  ungroup() %>%
  mutate(contTime = as.numeric(difftime(sent, start_pp, units="mins")) / unit)

Secondly, we can replace the ‘obsno’ variable with our continuous time variable in the previous plots. Here are two examples:

  1. One participant and multiple variables
  2. Multiple participants and one variable

data %>% filter(id==12) %>%
  gather(var, val, PA1:NA1) %>%
  ggplot(aes(x=contTime, y=val, color=var)) +
    geom_line() +
    facet_grid(var~., scales="free") +
    scale_x_continuous(breaks = seq(0,1000,24)) +  # 
    labs(x = "Time in hours")

Subset of participants

Because of the large number of participants, it is often difficult to get an overview of the time series characteristics, for instance, the variability across the Hence, it is useful to select plot time series from participants that can be representative of the sample. For instance, we can select participants with the highest, medium, and lowest variance in their time series. First, we compute the variance of the time series for each participant. Then, we select the participants with the highest, medium, and lowest variance. Finally, we plot the time series of these participants.

nb_pp = 4 # Number of participants per group

# Compute variance and mark participants
df_ppvar = data %>% 
  group_by(id) %>% 
  summarise(PA1_var=var(PA1, na.rm=TRUE)) %>%
  mutate(PA1_varc = abs(PA1_var - mean(PA1_var))) %>% 
  # Mark participant
  arrange(PA1_var) %>% mutate(var_order = row_number()) %>%
  arrange(PA1_varc) %>% mutate(varc_order = 1:n()) %>%
  mutate(var_group = case_when(
    var_order <= nb_pp ~ "low",
    var_order > (n()-nb_pp) ~ "high",
    varc_order <= nb_pp ~ "medium",
    TRUE ~ "other"
  )) 

# Plot time series
data %>%
  left_join(df_ppvar, by="id") %>%
  filter(var_group != "other") %>%
  ggplot(aes(x=obsno, y=PA1, color=factor(var_group), group=id)) +
    geom_line() +
    geom_point() 

Additional information

In the other topics of step 5, we introduce various time series plots that are useful to highlight different aspects or covariates of time series. We briefly give two examples here.

Distribution

When visualizing time series data, incorporating marginal density or histogram plots alongside the main series offers a swift means to examine the distribution of values across the scale. We propose two methods:

  • ‘ggMarginal()’ from the ggExtra package: it allows to add marginal density or histogram plots to a ggplot2 scatterplot.
  • ‘geom_rug()’ from the ggplot2 package: display the distribution of the variables with thin overlapping lines next to the x- or y-axis as a projection of the variables displayed in the plot.

library(ggExtra)
p = data %>% filter(id == 2) %>% 
  ggplot(aes(x=obsno, y=PA1)) +
    geom_line() +
    geom_point()
ggMarginal(p, margins = "y", type = "histogram")

See more about distributions in the Distribution plots section.

Temporal/context covariates

Plotting temporal/context covariates in time series can be valuable as it provides visual insights into the relationship between these covariates and the target variable(s) over time. Below, we explore how the time series covaries with another dichotomic variable (‘contact’).

data %>% 
  filter(id == 16) %>%
  ggplot(aes(x=obsno,y=PA1)) +
    geom_line() +
    geom_point() +
    geom_point(aes(color=factor(contact)),size=2)

Delimite periods of time

To further replace time series in their context, we can represent periods of time (e.g., days, weeks) in the plot. In the following plot, we want to explore the difference in dynamics between weekdays and weekend days. To do so, we color the lines and points according to the type of day.

data %>%
  filter(id == 13) %>%
  mutate(wday = ifelse(wday(sent) %in% c(1,7), "weekend", "weekday")) %>%
  ggplot(aes(x=obsno, y=PA1, color=factor(wday))) +
    geom_path(aes(group=1)) +  # here, use geom_path() rather than geom_line()
    geom_point()