Package {snakeplot}


Title: Serpentine Plots for Long Timeline, Sequential and Survey Data
Version: 0.4.0
Description: Visualize long timelines, extended sequences and temporally chained survey responses and experience sampling data using intuitive serpentine (snake) plots. Supports distribution bars, tick-mark plots, inter-item correlation arcs, faceted multi-construct panels, and daily time-of-day positioning for ecological momentary assessment data. Further plot types fold categorical state sequences, career timelines and daily activity logs into the same serpentine layout. All plots are drawn with base 'R' graphics.
License: MIT + file LICENSE
Depends: R (≥ 3.5.0)
Imports: graphics, grDevices, stats
LazyData: true
URL: https://github.com/mohsaqr/snakeplot, https://pak.dynasite.org/Snakeplot/
BugReports: https://github.com/mohsaqr/snakeplot/issues
Encoding: UTF-8
Config/testthat/edition: 3
Suggests: testthat (≥ 3.0.0), knitr, rmarkdown
VignetteBuilder: knitr
Config/roxygen2/version: 8.1.1
NeedsCompilation: no
Packaged: 2026-11-17 14:15:55 UTC; mohammedsaqr
Author: Mohammed Saqr [aut, cre, cph], Sonsoles Lopez-Pernas [aut]
Maintainer: Mohammed Saqr <saqr@saqr.me>
Repository: CRAN
Date/Publication: 2026-11-17 17:40:02 UTC

snakeplot: Serpentine Plots for Long Timeline, Sequential and Survey Data

Description

snakeplot draws serpentine ("snake") plots: displays in which a long ordered axis (days, time points, positions in a sequence or items of a questionnaire) is folded into parallel bands joined by U-turns. The whole axis fits in one panel, its order is kept, and neighbouring bands can be compared directly. All plots are drawn with base R graphics.

The package covers three kinds of data: event times and continuous measurements within days, categorical state sequences, and responses to rating items, including experience-sampling data collected several times a day. Each plot function draws on the current graphics device; the value it returns invisibly is described on its help page.

Details

Every plot shares the same layout. Bands are stacked from top to bottom; with flow = "snake" they alternate direction so that the axis runs on through each U-turn, and with flow = "natural" every band reads in the same direction, like lines of text. start_from chooses the side of the first band. Most functions default to "snake"; sequence_snake() and timeline_snake() default to "natural".

A serpentine changes the reading of distances. Positions at the ends of adjacent bands are close on the page but far apart on the axis. In activity_snake() and line_snake(), points above one another in adjacent bands share a time of day only when the bands read in the same direction (flow = "natural"). Band labels and U-turn labels give the position on the axis.

Time within days

activity_snake() shows event times, one band per day, as ticks or blocks of their duration. line_snake() draws a continuous series as a line through the days. facet_snake() draws one panel per group.

Sequences

sequence_snake() shows one long categorical sequence as colored blocks along the path. timeline_snake() builds a monthly sequence from phases with start and end dates, such as the positions in a career. multi_snake() shows many sequences as a sequence index or state distribution display (Gabadinho et al., 2011).

Survey and experience-sampling data

survey_snake() shows every response to each item as a tick, with the item mean, optional correlations between adjacent items, and a mode for experience-sampling data with one band per day. survey_sequence() and sequential_dist() show one 100% stacked bar per item, with diverging or single-hue colors (see Heiberger & Robbins, 2014, on stacked bars for rating scales). snake_palette() and snake_palettes provide colors for response levels.

Data

ema_emotions, student_survey and ema_beeps come from a 14-day experience-sampling study of university students (Neubauer & Schmiedek, 2024).

Author(s)

Maintainer: Mohammed Saqr saqr@saqr.me [copyright holder]

Authors:

References

Gabadinho, A., Ritschard, G., Müller, N. S., & Studer, M. (2011). Analyzing and visualizing state sequences in R with TraMineR. Journal of Statistical Software, 40(4), 1-37. doi:10.18637/jss.v040.i04

Heiberger, R. M., & Robbins, N. B. (2014). Design of diverging stacked bar charts for Likert scales and other applications. Journal of Statistical Software, 57(5), 1-32. doi:10.18637/jss.v057.i05

Neubauer, A. B., & Schmiedek, F. (2024). Approaching academic adjustment on multiple time scales. Zeitschrift fuer Erziehungswissenschaft, 27(1), 147-168. doi:10.1007/s11618-023-01182-8

See Also

Useful links:


Plot daily activity as a serpentine timeline of days

Description

activity_snake() draws an activity snake plot, which shows when events occur over many days. Each day is a band spanning the same time-of-day window, and consecutive days are joined by U-turns, so a long run of days fits in one panel while their order is kept. Events appear as thin ticks (instantaneous events) or as blocks whose width is the event's duration, which places daily rhythms, gaps and irregular days side by side for comparison.

The function takes event times as a vector of timestamps, a data frame of timestamps, or a data frame of day, start time and duration. It draws one band per day on a dark ribbon, with hourly gridlines, an hour axis, day labels carrying the day's total duration or number of events, and the clock time at each U-turn. Bands can alternate direction (flow = "snake") so that time runs on through each U-turn, or all read in the same direction (flow = "natural"); the layout can be horizontal or vertical. It returns the layout invisibly as a snake_layout object.

The display encodes the timing of events, not their values. For a continuous measurement through the day use line_snake(); for a sequence of categorical states use sequence_snake(); for ratings collected at each prompt use the var/day interface of survey_snake(). facet_snake() draws one activity snake plot per group.

Usage

activity_snake(
  data,
  band_height = 28,
  band_gap = 18,
  day_start = 360,
  day_end = 1440,
  plot_width = 500,
  band_color = "#3d3d4a",
  event_color = "#d4a843",
  arc_color = "#2a2a3a",
  band_opacity = 0.9,
  arc_opacity = 0.85,
  event_opacity = 0.85,
  tick_width = 1.5,
  show_grid = TRUE,
  show_total = TRUE,
  show_count = FALSE,
  show_hour_labels = TRUE,
  show_arc_labels = TRUE,
  shadow = TRUE,
  grid_color = "rgba(255,255,255,0.25)",
  label_color = "#cccccc",
  label_size = 0.85,
  label_align = "left",
  orientation = c("horizontal", "vertical"),
  start_from = c("left", "right"),
  flow = c("snake", "natural"),
  day_format = NULL,
  legend = NULL,
  title = NULL,
  margin = c(top = 30, right = 10, bottom = 50, left = 80),
  background = "white"
)

Arguments

data

Events, in one of three forms:

  • a POSIXct vector of event times;

  • a data frame with a POSIXct timestamp or start column, and optionally an end column (POSIXct) or a duration column (minutes);

  • a data frame with columns day (day label), start (minutes after midnight, 0-1440) and duration (minutes; 0 for an instantaneous event).

Column names are matched without regard to case, and common variants such as start_time, end_time or date are recognised. Character timestamps are parsed. Days appear in order of first occurrence.

band_height, band_gap

Height of each day band and gap between bands, in plot units (defaults 28 and 18).

day_start, day_end

Time window of each band, in minutes after midnight (defaults 360, 6 AM, and 1440, midnight). When data is a POSIXct vector, or a data frame whose timestamp or start column is POSIXct, the window is widened to whole hours covering all events.

plot_width

Length of each band in plot units (default 500).

band_color, event_color

Colors of the bands and of the events (defaults "#3d3d4a" and "#d4a843"). A vector of colors is recycled over days.

arc_color

Color of the U-turns (default "#2a2a3a").

band_opacity, arc_opacity, event_opacity

Opacities between 0 and 1 (defaults 0.90, 0.85 and 0.85).

tick_width

Minimum width of an event in plot units (default 1.5), which keeps instantaneous events visible.

show_grid

Draw hourly gridlines (default TRUE).

show_total

Append the day's total event duration to its label (default TRUE).

show_count

Append the day's number of events to its label (default FALSE).

show_hour_labels

Draw the hour axis (default TRUE).

show_arc_labels

Print the clock time at each U-turn (default TRUE).

shadow

Draw drop shadows (default TRUE).

grid_color

Gridline color: an R color or a CSS-style "rgba(r,g,b,a)" string (default "rgba(255,255,255,0.25)").

label_color, label_size

Color and size multiplier of the day labels (defaults "#cccccc" and 0.85).

label_align

Alignment of the day labels: "left" (default), "right", or "direction" to follow each band's reading direction.

orientation

"horizontal" (default) for bands running across the page, or "vertical" for bands running down it. The vertical layout uses smaller sizes and margins for those arguments left at their defaults.

start_from

Side on which the first band starts: "left" (default) or "right".

flow

"snake" (default): bands alternate direction, so time runs on through each U-turn. "natural": every band reads in the same direction.

day_format

strftime() format of day labels built from timestamps, such as "%a" or "%d %b". NULL (default) uses "%a" for up to seven days and "%Y-%m-%d" otherwise.

legend

Legend entries: a list of items, each a list with label and color, and optionally type ("rect", the default, "tick" or "gradient"). NULL (default) draws no legend.

title

Plot title, or NULL (default) for none.

margin

Named numeric vector of top, right, bottom and left margins in plot units (default c(top = 30, right = 10, bottom = 50, left = 80)).

background

Background color (default "white").

Value

The plot is drawn on the current device. The function returns, invisibly, an object of class snake_layout: a list describing the drawn geometry, with bands (a data frame with one row per day band giving its index, position, and drawing and reading direction), arcs (a list with one element per U-turn), canvas and plot_area (dimensions in plot units), orientation, flow and params (the sizes used).

See Also

line_snake() for a continuous value through the day; sequence_snake() for categorical states; survey_snake() for ratings at each prompt; facet_snake() for one panel per group.

Examples

# One participant's 69 prompts over 14 days of experience sampling
beeps <- subset(ema_beeps, id == "xcVDLRQOwn", select = start_time)
activity_snake(beeps, show_total = FALSE, show_count = TRUE)

# Sessions with durations: day, start (minutes after midnight), length
set.seed(1)
sessions <- data.frame(
  day      = rep(c("Mon", "Tue", "Wed", "Thu", "Fri"), each = 4),
  start    = round(runif(20, 420, 1260)),
  duration = round(runif(20, 20, 120))
)
activity_snake(sessions, event_color = "#E69F00", flow = "natural")


Extract the tables of a serpentine plot's layout

Description

as.data.frame() returns a table of a snake_layout object, chosen by what: the geometry of the bands, the correlations printed at the U-turns, or the size of the canvas. The plot functions return their layout invisibly as a snake_layout object.

Usage

## S3 method for class 'snake_layout'
as.data.frame(
  x,
  row.names = NULL,
  optional = FALSE,
  what = c("bands", "correlations", "canvas"),
  ...
)

Arguments

x

A snake_layout, as returned by survey_snake(), survey_sequence(), sequential_dist(), activity_snake() or line_snake().

row.names, optional

Not used; present for compatibility with the generic.

what

Which table: "bands" (default), "correlations" or "canvas".

...

Not used.

Value

A data frame.

Conditions

snakeplot_no_table when what = "correlations" and the plot was not drawn with arc_fill = "correlation".

See Also

survey_snake() for the correlation arcs.

Examples

layout <- survey_snake(ema_emotions, sort_by = "mean",
                       arc_fill = "correlation")
as.data.frame(layout, what = "correlations")
as.data.frame(layout)

Prompt-level happiness and anger ratings from an experience-sampling study

Description

ema_beeps is a dataset of all 11,474 answered prompts ("beeps") from a 14-day experience-sampling study of 321 university students (Neubauer & Schmiedek, 2024). Each row is one prompt with the participant, the study day, the time of the prompt and the ratings of happiness and anger, rescaled from 1-7 to 1-5 by round(1 + (x - 1) * 4 / 6). Participants answered between 1 and 69 prompts; the 14 study days of one participant need not be consecutive calendar days.

The data are in long format. With the var, day and timestamp arguments of survey_snake() each study day becomes a band and each rating is placed at its time of day; the prompt times of one participant can be shown with activity_snake().

Usage

ema_beeps

Format

A data frame with 11,474 rows (prompts) and 5 columns:

id

Character. Anonymised participant identifier.

day

Integer 1-14. Study day.

start_time

POSIXct (UTC). Time of the prompt, between April and July 2021.

happy

Integer 1-5. Rated happiness.

angry

Integer 1-5. Rated anger.

Source

Neubauer, A. B., & Schmiedek, F. (2024). Approaching academic adjustment on multiple time scales. Zeitschrift fuer Erziehungswissenschaft, 27(1), 147–168. doi:10.1007/s11618-023-01182-8

Data: https://osf.io/bhq3p | Codebook: https://osf.io/csfwg | Code: https://osf.io/84kdr/files | License: CC-BY 4.0

See Also

ema_emotions and student_survey for person-level ratings; survey_snake(); activity_snake().

Examples

# Anger over the 14 study days, each rating at its time of day
survey_snake(ema_beeps, var = "angry", day = "day",
             timestamp = "start_time")

# Happiness per study day as stacked bars
survey_snake(ema_beeps, var = "happy", day = "day", tick_shape = "bar")

# When one participant answered the prompts
activity_snake(subset(ema_beeps, id == "xcVDLRQOwn", select = start_time),
               show_total = FALSE, show_count = TRUE)

Person-level emotion ratings from an experience-sampling study

Description

ema_emotions is a dataset of the mean ratings of ten emotions for 280 university students who took part in a 14-day experience-sampling study (Neubauer & Schmiedek, 2024). Each value is a student's mean rating of one emotion over all prompts, rounded to a whole number and rescaled from the original 1-7 scale to 1-5 by round(1 + (x - 1) * 4 / 6). Students without a mean on every item of student_survey were excluded.

The data have one row per student and one column per emotion, the raw response format read by survey_snake(), survey_sequence() and sequential_dist(). Because the rows keep each student's answers together, correlations between items can be shown with survey_snake(arc_fill = "correlation"). The same values form the Emo_ columns of student_survey.

Usage

ema_emotions

Format

A data frame with 280 rows (students) and 10 integer columns with values 1-5: Happy, Afraid, Sad, Balanced, Exhausted, Cheerful, Worried, Lively, Angry, Relaxed.

Source

Neubauer, A. B., & Schmiedek, F. (2024). Approaching academic adjustment on multiple time scales. Zeitschrift fuer Erziehungswissenschaft, 27(1), 147–168. doi:10.1007/s11618-023-01182-8

Data: https://osf.io/bhq3p | Codebook: https://osf.io/csfwg | Code: https://osf.io/84kdr/files | License: CC-BY 4.0

See Also

student_survey for all 34 items; ema_beeps for the prompt-level data; survey_snake().

Examples

survey_snake(ema_emotions, tick_shape = "bar", sort_by = "mean")
survey_snake(ema_emotions, arc_fill = "correlation")

Draw one snake plot per group in a grid of panels

Description

facet_snake() splits a data frame by a grouping column and draws one snake plot per group in a grid of panels, so that groups such as participants, classes or conditions can be compared in the same display. Each panel is drawn by FUN, by default activity_snake(), with the group value as its title.

The panels are independent plots: each is scaled to its own data. The grid is set with par(mfrow) and the previous graphical parameters are restored afterwards. It returns, invisibly, a list with the value FUN returned for each panel.

To draw groups of items (columns) rather than groups of rows, use the facet argument of survey_snake().

Usage

facet_snake(data, facet_var, FUN = activity_snake, ncol = NULL, ...)

Arguments

data

A data frame. It is split by facet_var, and each part, without the grouping column, is passed to FUN as its first argument.

facet_var

Name of the grouping column. Panels follow the order in which its values first appear.

FUN

Plotting function for each panel (default activity_snake()). It must take the data as its first argument and accept a title argument; line_snake(), survey_snake(), survey_sequence() and sequential_dist() qualify.

ncol

Number of panel columns. NULL (default) places all panels in one row.

...

Further arguments passed to FUN.

Value

The panels are drawn on the current device. The function returns, invisibly, an unnamed list with one element per group, in order of first appearance, holding the value FUN returned for that panel (a snake_layout object for activity_snake()).

See Also

activity_snake(), survey_snake() and its facet argument.

Examples

# Two participants' prompts, one panel each
two <- subset(ema_beeps, id %in% c("xcVDLRQOwn", "6pig43CFyl"),
              select = c(id, start_time))
facet_snake(two, facet_var = "id", ncol = 1, show_total = FALSE)


Plot a continuous series as a line through a serpentine of days

Description

line_snake() draws a line snake plot, which shows a continuous measurement, such as foot traffic or a sensor reading, over many days. Each day is a band covering the same time-of-day window; within a band the height of the line encodes the value, and the line continues through the U-turn into the next day. The series stays unbroken while each day can be compared with the days above and below it.

The function takes a data frame of times and values, optionally with a day column, or a numeric vector drawn as one band of evenly spaced values. The value axis is shared by all bands and runs from the overall minimum to the overall maximum. An optional fill shades the area under the line. It returns the layout invisibly as a snake_layout object. The interface of this function is experimental and may change in a later release.

For the timing of discrete events use activity_snake(); for categorical states use sequence_snake().

Usage

line_snake(
  data,
  band_height = 40,
  band_gap = 18,
  day_start = 0,
  day_end = 1440,
  plot_width = 500,
  line_color = "#e74c3c",
  line_width = 1.5,
  fill_color = NULL,
  fill_opacity = 0.3,
  band_color = "#2d2d3d",
  arc_color = "#1a1a2e",
  band_opacity = 0.9,
  arc_opacity = 0.85,
  show_grid = TRUE,
  shadow = TRUE,
  label_color = "#cccccc",
  label_size = 0.85,
  orientation = c("horizontal", "vertical"),
  start_from = c("left", "right"),
  flow = c("snake", "natural"),
  title = NULL,
  margin = c(top = 30, right = 10, bottom = 50, left = 80),
  background = "white"
)

Arguments

data

A data frame with columns time (minutes after midnight, or POSIXct), value (numeric) and optionally day (band label). With POSIXct times the band label is the abbreviated weekday, so times more than a week apart share a band. A numeric vector is drawn as a single band.

band_height, band_gap

Height of each band and gap between bands, in plot units (defaults 40 and 18).

day_start, day_end

Time window of each band, in minutes after midnight (defaults 0 and 1440).

plot_width

Length of each band in plot units (default 500).

line_color, line_width

Color and width of the line (defaults "#e74c3c" and 1.5).

fill_color, fill_opacity

Color of the area under the line, NULL (default) for no fill, and its opacity (default 0.3).

band_color, arc_color

Colors of the bands and U-turns (defaults "#2d2d3d" and "#1a1a2e").

band_opacity, arc_opacity

Opacities between 0 and 1 (defaults 0.90 and 0.85).

show_grid

Draw hourly gridlines (default TRUE).

shadow

Draw drop shadows (default TRUE).

label_color, label_size

Color and size multiplier of the band labels (defaults "#cccccc" and 0.85).

orientation

Only "horizontal" (default) is supported at present; "vertical" gives an error.

start_from

Side on which the first band starts: "left" (default) or "right".

flow

"snake" (default): bands alternate direction, so time runs on through each U-turn. "natural": every band reads in the same direction.

title

Plot title, or NULL (default) for none.

margin

Named numeric vector of top, right, bottom and left margins in plot units (default c(top = 30, right = 10, bottom = 50, left = 80)).

background

Background color (default "white").

Value

The plot is drawn on the current device. The function returns, invisibly, an object of class snake_layout: a list describing the drawn geometry, with bands (a data frame with one row per band giving its index, position, and drawing and reading direction), arcs (a list with one element per U-turn), canvas and plot_area (dimensions in plot units), orientation, flow and params (the sizes used).

See Also

activity_snake() for event times; sequence_snake() for categorical states; facet_snake() for one panel per group.

Examples

# Four days of a value measured every 10 minutes
set.seed(42)
minutes <- seq(0, 1440, by = 10)
traffic <- data.frame(
  day   = rep(c("Mon", "Tue", "Wed", "Thu"), each = length(minutes)),
  time  = rep(minutes, 4),
  value = 50 + 50 * sin(rep(minutes, 4) / 1440 * 4 * pi) +
    rnorm(4 * length(minutes), 0, 8)
)
line_snake(traffic, line_color = "#D55E00", fill_color = "#D55E00")


Plot many state sequences as a serpentine index or distribution plot

Description

multi_snake() draws a multi-sequence snake plot, which shows a set of categorical sequences, such as the weekly activity states of a class of students, with their common time axis folded into bands joined by U-turns. Each time point is a block along the serpentine path, so long sequences fit in one panel while the order of time points is kept.

Two displays are available. With type = "index" each block holds one thin tick per sequence, colored by that sequence's state at the time point, as in a sequence index plot; every sequence keeps the same position in all blocks, and sequences can be ordered with sort_by. With type = "distribution" each block is a stacked bar of the share of sequences in each state at that time point, as in a state distribution plot (Gabadinho et al., 2011). The U-turns are neutral connectors: time points that fall on a U-turn are not drawn, and the label of each band gives the range of time points it shows. The plot is drawn on the current device and NULL is returned invisibly.

For a single long sequence use sequence_snake(); for phases with start and end dates use timeline_snake(). Distributions of ordinal survey responses are shown by survey_sequence().

Usage

multi_snake(
  sequences,
  type = c("index", "distribution"),
  states = NULL,
  colors = NULL,
  sort_by = c("none", "first", "last", "freq", "entropy"),
  rows = NULL,
  band_height = 28,
  band_gap = 18,
  plot_width = 500,
  margin = c(top = 30, right = 10, bottom = 50, left = 80),
  flow = c("snake", "natural"),
  show_labels = TRUE,
  show_legend = TRUE,
  show_percent = TRUE,
  border_color = NA,
  title = NULL,
  background = "white",
  shadow = TRUE,
  legend_text_size = 0.8,
  tick_opacity = 0.85
)

Arguments

sequences

A matrix or data frame with one row per sequence and one column per time point; cells hold state labels. Column names, if any, label the time points.

type

"index" (default) or "distribution".

states

State labels in the order used for the legend and for sorting. NULL (default) takes them in order of first appearance.

colors

State colors: a vector named by state, or an unnamed vector recycled over states. States missing from a named vector are drawn in grey. NULL (default) uses a built-in qualitative palette.

sort_by

Order of the sequences in the index display: "none" (default, input order), "first" or "last" (by the state at the first or last time point), "freq" (by each sequence's most frequent state) or "entropy" (by increasing Shannon entropy of its states). Ignored for type = "distribution".

rows

Number of bands. NULL (default) uses one band per 11 time points, rounded up.

band_height, band_gap

Height of each band and gap between bands, in plot units (defaults 28 and 18).

plot_width

Length of each band in plot units (default 500).

margin

Named numeric vector of top, right, bottom and left margins in plot units (default c(top = 30, right = 10, bottom = 50, left = 80)).

flow

"snake" (default): bands alternate direction. "natural": every band reads in the same direction.

show_labels

Label each band with the range of time points it shows (default TRUE).

show_legend

Draw the state legend and the number of sequences (default TRUE).

show_percent

Print percentages inside distribution segments wide enough to hold them (default TRUE).

border_color

Color of block outlines, or NA (default) for none.

title

Plot title, or NULL (default) for none.

background

Background color (default "white").

shadow

Draw drop shadows (default TRUE).

legend_text_size

Size of the legend text (default 0.8).

tick_opacity

Opacity of the ticks in the index display, between 0 and 1 (default 0.85).

Value

The plot is drawn on the current device; the function returns NULL invisibly.

References

Gabadinho, A., Ritschard, G., Müller, N. S., & Studer, M. (2011). Analyzing and visualizing state sequences in R with TraMineR. Journal of Statistical Software, 40(4), 1-37. doi:10.18637/jss.v040.i04

See Also

sequence_snake() for one sequence; timeline_snake() for dated phases; survey_sequence() for ordinal survey responses.

Examples

# 50 students observed over 33 weeks
set.seed(42)
weeks <- matrix(
  sample(c("Active", "Passive", "Absent"), 50 * 33, replace = TRUE,
         prob = c(0.5, 0.3, 0.2)),
  nrow = 50
)
multi_snake(weeks, sort_by = "freq",
            colors = c(Active = "#009E73", Passive = "#E69F00",
                       Absent = "#999999"))
multi_snake(weeks, type = "distribution")


Plot a long state sequence as blocks along a serpentine path

Description

sequence_snake() draws a sequence snake plot, which shows one long categorical sequence, such as the actions in a learning session or a person's daily states over months, as a row of colored blocks, one per position. The row is folded into bands joined by U-turns, and the blocks continue through the U-turns, so a sequence of several hundred positions fits in one panel while the order of positions is kept. Runs, recurrences and changes of state can be followed along the path, as in a sequence index plot of a single sequence (Gabadinho et al., 2011).

The function accepts the sequence as a vector, a comma-separated string, a list, or a data frame whose first character or factor column holds the states. Blocks can carry position numbers, state names or other labels, and the path can be annotated with ruler ticks, a label for each band and labels at changes of state. With style = "rug" blocks become thin ticks on a light band, which keeps many positions legible. The plot is drawn on the current device and NULL is returned invisibly.

For many sequences at once use multi_snake(). For phases defined by start and end dates use timeline_snake(), which builds the monthly sequence and its labels from the dates.

Usage

sequence_snake(
  sequence,
  states = NULL,
  colors = NULL,
  rows = NULL,
  band_height = 28,
  band_gap = 18,
  plot_width = 500,
  margin = c(top = 30, right = 10, bottom = 50, left = 80),
  orientation = "horizontal",
  start_from = "left",
  flow = c("natural", "snake"),
  show_labels = TRUE,
  show_legend = TRUE,
  show_numbers = FALSE,
  show_state = FALSE,
  state_size = 0.35,
  show_ticks = FALSE,
  tick_labels = NULL,
  transition_labels = NULL,
  transition_pos = NULL,
  tick_color = "#333333",
  tick_length = 5,
  tick_size = 0.4,
  style = c("block", "rug"),
  band_color = "#3d3d4a",
  rug_opacity = 0.9,
  jitter = 0,
  border_color = NA,
  block_labels = NULL,
  band_labels = NULL,
  title = NULL,
  background = "white",
  shadow = TRUE,
  text_size = 0.5,
  legend_text_size = 0.8
)

Arguments

sequence

The states in order: a character, factor or integer vector; a single comma-separated string such as "A,B,C"; a list; or a data frame, whose first character or factor column is used. Missing values are dropped with a warning.

states

State labels in legend order. NULL (default) takes them in order of first appearance. Every state in sequence must be listed.

colors

State colors: a vector named by state, or an unnamed vector recycled over states. States missing from a named vector are drawn in grey. NULL (default) uses a built-in qualitative palette.

rows

Number of bands. NULL (default) uses one band per 11 positions, rounded up.

band_height

Height of each band in plot units (default 28).

band_gap

Gap between bands in plot units (default 18).

plot_width

Length of each band in plot units (default 500).

margin

Named numeric vector of top, right, bottom and left margins in plot units (default c(top = 30, right = 10, bottom = 50, left = 80)).

orientation

"horizontal" (default). "vertical" turns the bands into columns but places the blocks across each column rather than along it, so the horizontal layout is recommended.

start_from

Side on which the first band starts: "left" (default) or "right".

flow

"natural" (default): every band reads in the same direction, like lines of text. "snake": bands alternate direction, so the sequence runs on through each U-turn.

show_labels

Label each band with the range of positions it holds (default TRUE).

show_legend

Draw the state legend (default TRUE).

show_numbers

Print each block's position inside it (default FALSE).

show_state

Print the state name inside each block (default FALSE).

state_size

Text size of the state names (default 0.35).

show_ticks

Draw ruler ticks at block boundaries, outside the bands (default FALSE).

tick_labels

Labels for evenly spaced ruler marks on every band, such as month.abb. Setting them turns on show_ticks.

transition_labels

Labels for the points where the state changes, in order; the first length(transition_labels) changes are labelled.

transition_pos

Positions of transition_labels along the sequence, in blocks; fractions such as 6.5 are allowed. NULL (default) places the labels at the changes of state.

tick_color

Color of ticks and of band and transition labels (default "#333333").

tick_length

Length of ticks in plot units (default 5).

tick_size

Text size of tick, band and transition labels (default 0.4).

style

"block" (default) fills each band with blocks; "rug" draws thin ticks on a light band, suited to sequences with many positions.

band_color

Not used at present; rug bands are drawn light grey.

rug_opacity

Opacity of the rug ticks, between 0 and 1 (default 0.9).

jitter

For style = "rug", vertical scatter of the ticks as a fraction of the band height (default 0, none). The scatter is random; call set.seed() first for a reproducible plot.

border_color

Color of block outlines, or NA (default) for none.

block_labels

Labels for the blocks, one per position. They replace the position numbers, and are drawn below the blocks when ruler ticks are shown.

band_labels

One label per band (length rows), printed below the band, for example a year.

title

Plot title, or NULL (default) for none.

background

Background color (default "white").

shadow

Draw drop shadows (default TRUE).

text_size

Text size of block numbers and block labels (default 0.5).

legend_text_size

Size of the legend text (default 0.8).

Value

The plot is drawn on the current device; the function returns NULL invisibly.

References

Gabadinho, A., Ritschard, G., Müller, N. S., & Studer, M. (2011). Analyzing and visualizing state sequences in R with TraMineR. Journal of Statistical Software, 40(4), 1-37. doi:10.18637/jss.v040.i04

See Also

timeline_snake() for dated phases; multi_snake() for many sequences; activity_snake() for event times within days.

Examples

# 75 actions in a learning session
set.seed(42)
actions <- sample(c("Read", "Write", "Discuss", "Plan", "Review"), 75,
                  replace = TRUE)
sequence_snake(actions)
sequence_snake(actions, rows = 5, flow = "snake", show_state = TRUE,
               colors = c(Read = "#56B4E9", Write = "#E69F00",
                          Discuss = "#009E73", Plan = "#CC79A7",
                          Review = "#999999"))

# 400 observations of on- and off-task behaviour as a rug
on_task <- sample(c("On task", "Off task"), 400, replace = TRUE,
                  prob = c(0.8, 0.2))
sequence_snake(on_task, style = "rug", rows = 8)


Plot unipolar survey responses as a serpentine of single-hue stacked bars

Description

sequential_dist() draws the survey sequence plot of survey_sequence(), one 100% stacked bar per item along a serpentine, with a light-to-dark palette of a single hue, so that darker segments stand for higher levels. It is meant for rating scales with no neutral midpoint: frequency scales from "Never" to "Always", or intensity scales from "Not at all" to "Extremely". For such scales a diverging palette suggests a midpoint the scale does not have.

Input, sorting, labels and layout options are those of survey_sequence(); hue sets the color of the palette. It returns the value of survey_sequence(), a snake_layout object, invisibly. For bipolar (agree-disagree) scales use survey_sequence(); to show individual responses use survey_snake().

Usage

sequential_dist(
  counts,
  labels = NULL,
  levels = NULL,
  hue = 210,
  band_height = 28,
  band_gap = 14,
  plot_width = 500,
  colors = NULL,
  show_percent = TRUE,
  min_segment = 34,
  arc_style = c("gradient", "neutral"),
  arc_opacity = 0.85,
  sort_by = c("none", "mean", "net"),
  shadow = TRUE,
  show_legend = TRUE,
  label_color = "#333333",
  label_size = 0.85,
  label_align = "left",
  reverse_rtl = FALSE,
  start_from = c("left", "right"),
  flow = c("snake", "natural"),
  title = NULL,
  margin = c(top = 30, right = 10, bottom = 55, left = 100),
  background = "white"
)

Arguments

counts

Responses: a data frame of raw responses (one row per respondent, one column per item), a numeric matrix of counts (items in rows, response levels in columns), or a data frame of counts. A data frame is read as raw responses when its columns hold few distinct whole-number or categorical values relative to its number of rows.

labels

Item labels, one per item. NULL (default) uses the row names of a count table, or, for raw responses, the column names with the number of responses.

levels

Response levels in scale order. NULL (default) uses the column names of a count table, or, for raw responses, the factor levels or the sorted distinct values. For raw responses the levels must match the values in the data.

hue

Hue of the palette in degrees, 0-360 (default 210, blue).

band_height

Height of each band in plot units (default 28).

band_gap

Gap between bands in plot units (default 14).

plot_width

Length of each band in plot units (default 500).

colors

One color per response level, in scale order. NULL (default) uses a light-to-dark palette of hue.

show_percent

Print percentages inside the segments (default TRUE).

min_segment

Minimum segment width, in plot units, for a percentage to be printed (default 34).

arc_style

"gradient" (default) colors each U-turn midway between the levels at its two ends; "neutral" draws it grey.

arc_opacity

Opacity of the U-turns, between 0 and 1 (default 0.85).

sort_by

Order of the items: "none" (default, input order), "mean" (increasing item mean) or "net" (increasing share of responses above the middle level minus share below; the mean for scales with fewer than four levels).

shadow

Draw drop shadows (default TRUE).

show_legend

Draw the legend (default TRUE).

label_color, label_size

Color and size multiplier of the item labels (defaults "#333333" and 0.85).

label_align

Alignment of the item labels: "left" (default), "right", or "direction" to follow each band's reading direction.

reverse_rtl

Reverse the order of levels on bands that read right to left, so every band starts with the lowest level in its reading direction (default FALSE: lowest level on the left of every band).

start_from

Side on which the first band starts: "left" (default) or "right".

flow

"snake" (default): bands alternate direction. "natural": every band reads in the same direction.

title

Plot title, or NULL (default) for none.

margin

Named numeric vector of top, right, bottom and left margins in plot units (default c(top = 30, right = 10, bottom = 55, left = 100)).

background

Background color (default "white").

Value

The value of survey_sequence(): the plot is drawn on the current device and an object of class snake_layout is returned invisibly.

References

Heiberger, R. M., & Robbins, N. B. (2014). Design of diverging stacked bar charts for Likert scales and other applications. Journal of Statistical Software, 57(5), 1-32. doi:10.18637/jss.v057.i05

See Also

survey_sequence() for diverging colors; survey_snake() for individual responses; snake_palette() for the sequential palettes "blues", "greens", "grays", "warm" and "viridis".

Examples

# Emotion intensity rated 1-5, a unipolar scale
sequential_dist(ema_emotions, sort_by = "mean", hue = 160)

# A table of counts on a frequency scale
counts <- matrix(c(15, 25, 60, 80, 45,
                   10, 20, 50, 90, 55,
                   20, 30, 65, 70, 40),
                 nrow = 3, byrow = TRUE)
sequential_dist(counts,
                labels = c("Plans study time", "Reviews notes",
                           "Asks for help"),
                levels = c("Never", "Rarely", "Sometimes", "Often",
                           "Always"))


Get a built-in palette for snake plots

Description

snake_palette() returns one of the palettes in snake_palettes, interpolated to n colors. The survey plots match colors to response levels by position and use only the first length(levels) colors, so n should equal the number of response levels for a palette to span the whole scale; a diverging palette then has its midpoint at the middle level.

Diverging palettes (classic, earth, ocean, sunset, berry) suit bipolar scales; sequential palettes (blues, greens, grays, warm, viridis) suit unipolar scales and sequential_dist().

Usage

snake_palette(name = "classic", n = 7L)

Arguments

name

Palette name, one of names(snake_palettes) (default "classic"). An unknown name is an error that lists the available names.

n

Number of colors (default 7). With 7 the anchor colors are returned unchanged; other values interpolate between them with grDevices::colorRampPalette().

Value

A character vector of n hex colors, ordered from the low to the high end of the scale.

See Also

snake_palettes for the anchor colors; survey_snake(), survey_sequence() and sequential_dist(), which take the colors through their colors argument.

Examples

snake_palette("ocean", n = 5)
snake_palette("blues", n = 3)
survey_sequence(ema_emotions, colors = snake_palette("berry", n = 5))


Built-in color palettes for snake plots

Description

snake_palettes is a named list of ten palettes for the response levels of rating scales. Each palette has seven anchor colors ordered from the low to the high end of the scale; snake_palette() returns a palette by name and interpolates it to the number of levels in the data.

Five palettes are diverging, with a grey midpoint, for bipolar scales such as agree-disagree: classic (red to blue), earth (brown to teal), ocean (red to blue through orange), sunset (orange to purple) and berry (pink to green). Five are sequential, light to dark, for unipolar scales such as frequency or intensity: blues, greens, grays, warm (cream to dark red) and viridis (yellow to blue, colors from the viridis scale).

Usage

snake_palettes

Format

A named list of 10 character vectors, each holding 7 hex color strings from the low to the high end of the scale.

See Also

snake_palette() to get a palette with a given number of colors; survey_snake(), survey_sequence() and sequential_dist(), which take the colors through their colors argument.

Examples

names(snake_palettes)

# ema_emotions has 5 levels, so interpolate the palette to 5 colors
survey_snake(ema_emotions, colors = snake_palette("earth", n = 5),
             tick_shape = "bar", sort_by = "mean")


Person-level ratings of emotion, motivation, regulation and engagement

Description

student_survey is a dataset of the mean ratings of 34 items for the 280 university students of ema_emotions, from the same 14-day experience-sampling study (Neubauer & Schmiedek, 2024). Each value is a student's mean rating of one item over all prompts, rounded to a whole number and rescaled from 1-7 to 1-5 by round(1 + (x - 1) * 4 / 6).

The items belong to four constructs, marked by a column-name prefix, so that survey_snake(student_survey, facet = TRUE) draws one panel per construct:

Usage

student_survey

Format

A data frame with 280 rows (students) and 34 integer columns with values 1-5, named ⁠<prefix>_<item>⁠ as listed above.

Source

Neubauer, A. B., & Schmiedek, F. (2024). Approaching academic adjustment on multiple time scales. Zeitschrift fuer Erziehungswissenschaft, 27(1), 147–168. doi:10.1007/s11618-023-01182-8

Data: https://osf.io/bhq3p | Codebook: https://osf.io/csfwg | Code: https://osf.io/84kdr/files | License: CC-BY 4.0

See Also

ema_emotions for the emotion items alone; ema_beeps for the prompt-level data; survey_snake() and its facet argument.

Examples

survey_snake(student_survey, facet = TRUE, tick_shape = "bar",
             sort_by = "mean", facet_ncol = 2L)

Plot survey responses as a serpentine of stacked bars

Description

survey_sequence() draws a survey sequence plot, which shows the distribution of responses to a set of rating items as one 100% stacked bar per item. The bars are the bands of a serpentine joined by U-turns, so a long instrument fits in one panel in its item order and the share of each response level can be compared between items. Heiberger and Robbins (2014) discuss the design of stacked bar charts for rating scales.

The function accepts raw responses or a table of counts. Segments are colored by response level, with a diverging palette by default, and carry their percentage when wide enough. Items can be sorted by mean or by net agreement. Each U-turn takes the color midway between the levels at the two ends it joins, or a neutral grey. It returns the layout invisibly as a snake_layout object.

sequential_dist() draws the same display with a single-hue palette for scales without a neutral midpoint. survey_snake() shows each response as a tick and can show correlations between adjacent items.

Usage

survey_sequence(
  counts,
  labels = NULL,
  levels = NULL,
  band_height = 28,
  band_gap = 14,
  plot_width = 500,
  colors = NULL,
  show_percent = TRUE,
  min_segment = 34,
  arc_style = c("gradient", "neutral"),
  arc_opacity = 0.5,
  sort_by = c("none", "mean", "net"),
  shadow = TRUE,
  show_legend = TRUE,
  label_color = "#333333",
  label_size = 0.85,
  label_align = "left",
  reverse_rtl = FALSE,
  start_from = c("left", "right"),
  flow = c("snake", "natural"),
  title = NULL,
  margin = c(top = 30, right = 10, bottom = 55, left = 100),
  background = "white"
)

Arguments

counts

Responses: a data frame of raw responses (one row per respondent, one column per item), a numeric matrix of counts (items in rows, response levels in columns), or a data frame of counts. A data frame is read as raw responses when its columns hold few distinct whole-number or categorical values relative to its number of rows.

labels

Item labels, one per item. NULL (default) uses the row names of a count table, or, for raw responses, the column names with the number of responses.

levels

Response levels in scale order. NULL (default) uses the column names of a count table, or, for raw responses, the factor levels or the sorted distinct values. For raw responses the levels must match the values in the data.

band_height

Height of each band in plot units (default 28).

band_gap

Gap between bands in plot units (default 14).

plot_width

Length of each band in plot units (default 500).

colors

One color per response level, in scale order. Only the first length(levels) colors are used, so pass ⁠snake_palette(name, n = <number of levels>)⁠. NULL (default) uses a red-to-blue diverging palette.

show_percent

Print percentages inside the segments (default TRUE).

min_segment

Minimum segment width, in plot units, for a percentage to be printed (default 34).

arc_style

"gradient" (default) colors each U-turn midway between the levels at its two ends; "neutral" draws it grey.

arc_opacity

Opacity of the U-turns, between 0 and 1 (default 0.5).

sort_by

Order of the items: "none" (default, input order), "mean" (increasing item mean) or "net" (increasing share of responses above the middle level minus share below; the mean for scales with fewer than four levels).

shadow

Draw drop shadows (default TRUE).

show_legend

Draw the legend (default TRUE).

label_color, label_size

Color and size multiplier of the item labels (defaults "#333333" and 0.85).

label_align

Alignment of the item labels: "left" (default), "right", or "direction" to follow each band's reading direction.

reverse_rtl

Reverse the order of levels on bands that read right to left, so every band starts with the lowest level in its reading direction (default FALSE: lowest level on the left of every band).

start_from

Side on which the first band starts: "left" (default) or "right".

flow

"snake" (default): bands alternate direction. "natural": every band reads in the same direction.

title

Plot title, or NULL (default) for none.

margin

Named numeric vector of top, right, bottom and left margins in plot units (default c(top = 30, right = 10, bottom = 55, left = 100)).

background

Background color (default "white").

Value

The plot is drawn on the current device. The function returns, invisibly, an object of class snake_layout: a list describing the drawn geometry, with bands (a data frame with one row per item band giving its index, position, and drawing and reading direction), arcs (a list with one element per U-turn), canvas and plot_area (dimensions in plot units), orientation, flow and params (the sizes used).

References

Heiberger, R. M., & Robbins, N. B. (2014). Design of diverging stacked bar charts for Likert scales and other applications. Journal of Statistical Software, 57(5), 1-32. doi:10.18637/jss.v057.i05

See Also

sequential_dist() for single-hue bars; survey_snake() for individual responses and item correlations; snake_palette() for level colors.

Examples

# Ten emotion items, sorted by net score
survey_sequence(ema_emotions, sort_by = "net")

# Study motivation items with another diverging palette
motivation <- subset(student_survey,
                     select = Mot_Disappointed:Mot_Enjoyment)
survey_sequence(motivation, sort_by = "mean",
                colors = snake_palette("ocean", n = 5))


Plot survey responses as a serpentine band per item

Description

survey_snake() draws a survey snake plot, which shows the distribution of responses to a set of rating items, one band per item, with consecutive items joined by U-turns so that a long instrument fits in one panel in its item order. Each band shows every response as a tick placed in the zone of its response level, the item mean as a diamond, and a shade running from warm (low mean) to cool (high mean). The display shows how responses are spread on each item and how the items compare.

The function accepts raw responses (one row per respondent, one column per item), a table of counts (one row per item, one column per response level), or experience-sampling data in long format, where var and day make each day a band and timestamp places each response at its time of day. Responses can be drawn as lines, jittered dots, or a stacked bar with percentages. The U-turns can carry the Pearson correlation between the two items they join (arc_fill = "correlation"); this needs raw responses, because a table of counts does not record which respondent gave which answer. With facet, groups of items are drawn as separate panels. It returns the layout invisibly as a snake_layout object, or a list of them with facet.

For a compact 100% stacked bar per item use survey_sequence(), or sequential_dist() for scales without a neutral midpoint. Palettes for the response levels are given by snake_palette().

Usage

survey_snake(
  counts,
  labels = NULL,
  levels = NULL,
  var = NULL,
  day = NULL,
  timestamp = NULL,
  level_labels = NULL,
  band_height = 28,
  band_gap = 18,
  plot_width = 500,
  tick_shape = c("line", "dot", "bar"),
  bar_reverse = FALSE,
  tick_opacity = 0.75,
  level_gap = 15,
  color_mode = c("level", "individual"),
  colors = NULL,
  shade_band = TRUE,
  show_mean = TRUE,
  show_median = FALSE,
  show_correlation = TRUE,
  jitter_range = 0.22,
  sort_by = c("none", "mean", "net"),
  shadow = TRUE,
  label_color = "#333333",
  label_size = 0.85,
  label_align = "left",
  show_legend = TRUE,
  legend_text_size = 0.65,
  arc_color = "#2c3e6b",
  arc_opacity = 0.8,
  arc_fill = c("none", "correlation", "mean_prev", "blend"),
  band_palette = NULL,
  start_from = c("left", "right"),
  flow = c("snake", "natural"),
  facet = FALSE,
  facet_ncol = 2L,
  title = NULL,
  margin = c(top = 30, right = 10, bottom = 55, left = 100),
  background = "white",
  seed = 42L
)

Arguments

counts

Responses, in one of four forms:

  • a data frame of raw responses, one row per respondent and one column per item;

  • a numeric matrix of counts, items in rows and response levels in columns;

  • a data frame of counts, converted to a matrix;

  • a long data frame of experience-sampling responses, used with var and day.

A data frame is read as raw responses when its columns hold few distinct whole-number or categorical values relative to its number of rows, and as counts otherwise.

labels

Item labels, one per item. NULL (default) uses the row names of a count table, or, for raw responses, the column names with the number of responses.

levels

Response levels in scale order. NULL (default) uses the column names of a count table, or, for raw responses, the factor levels or the sorted distinct values. For raw responses the levels must match the values in the data; use level_labels to relabel them.

var, day, timestamp

Column names for experience-sampling data in long format: the response variable, the day (or other period) that defines each band, and optionally a POSIXct timestamp that places each response at its time of day. Bands are labelled "Day 1", "Day 2", and so on, and title defaults to var.

level_labels

Display labels for the response levels: a vector named by level, such as c("1" = "Never", "5" = "Always"), or an unnamed vector with one label per level.

band_height, band_gap

Height of each band and gap between bands, in plot units (defaults 28 and 18).

plot_width

Length of each band in plot units (default 500).

tick_shape

"line" (default), "dot" (jittered points) or "bar" (a stacked bar with percentages).

bar_reverse

For tick_shape = "bar", draw the highest level first (default FALSE).

tick_opacity

Opacity of the ticks, between 0 and 1 (default 0.75).

level_gap

Gap, in plot units, between the zones of adjacent response levels (default 15; 0 for none).

color_mode

"level" (default) colors each tick by its response level; "individual" gives every tick its own hue.

colors

One color per response level, in scale order. Only the first length(levels) colors are used, so pass ⁠snake_palette(name, n = <number of levels>)⁠. NULL (default) uses a red-to-blue diverging palette.

shade_band

Has no effect at present: the band is always shaded by the item mean.

show_mean

Draw a diamond at the item mean (default TRUE).

show_median

Draw a dashed line at the item median (default FALSE).

show_correlation

With arc_fill = "correlation", print the correlation at each U-turn (default TRUE).

jitter_range

For tick_shape = "dot", vertical scatter of the points as a fraction of half the band height (default 0.22).

sort_by

Order of the items: "none" (default, input order), "mean" (increasing item mean) or "net" (increasing share of responses above the middle level minus share below; the mean for scales with fewer than four levels).

shadow

Draw drop shadows (default TRUE).

label_color, label_size

Color and size multiplier of the item labels (defaults "#333333" and 0.85).

label_align

Alignment of the item labels: "left" (default), "right", or "direction" to follow each band's reading direction.

show_legend

Draw the legend (default TRUE).

legend_text_size

Size of the legend text (default 0.65).

arc_color

Color of the U-turns for a positive correlation when arc_fill = "correlation"; a negative correlation uses its complement (default "#2c3e6b").

arc_opacity

Opacity of the U-turns for arc_fill = "mean_prev" and "blend", and of U-turns without a correlation (default 0.80).

arc_fill

Fill of the U-turns: "none" (default) continues the shades of the two bands it joins; "correlation" tints it by the Pearson correlation between the two items, darker for a larger absolute value; "mean_prev" uses the shade of the preceding item; "blend" mixes the two shades.

band_palette

Two or more colors for the band shade, from low to high item mean. NULL (default) uses a dark brown-to-slate ramp.

start_from

Side on which the first band starts: "left" (default) or "right".

flow

"snake" (default): bands alternate direction. "natural": every band reads in the same direction.

facet

FALSE (default) for one panel. TRUE groups the columns of raw responses by name prefix (LOC1, LOC2 become LOC; Emo_Happy becomes Emo) and draws one panel per group, with the prefix removed from the item labels and one shared legend in a spare panel. A named list of column-name vectors gives the groups explicitly.

facet_ncol

Number of panel columns for facet (default 2).

title

Plot title, or NULL (default) for none.

margin

Named numeric vector of top, right, bottom and left margins in plot units (default c(top = 30, right = 10, bottom = 55, left = 100)).

background

Background color (default "white").

seed

Seed for the random placement of ticks within their zones (default 42), so the same call draws the same plot. The session's random number state is restored when the function returns.

Value

The plot is drawn on the current device. The function returns, invisibly, an object of class snake_layout: a list describing the drawn geometry, with bands (a data frame with one row per item band and columns i, y_center, y_top, y_bottom, x_left, x_right, direction and read_direction), arcs (a list with one element per U-turn), canvas and plot_area (dimensions in plot units), orientation, flow and params (the sizes used).

With arc_fill = "correlation" the list also holds correlations, a data frame with one row per U-turn and columns from and to (the item names), r (the Pearson correlation over the respondents who answered both items; NA when fewer than three did or either item is constant among them) and n (the number of those respondents). With other arc_fill values the list has no correlations component. as.data.frame() returns these tables.

With facet, a named list of such objects, one per panel.

Conditions

An error of class snakeplot_no_respondent_data when arc_fill = "correlation" and counts is a table of counts or var and day are given.

See Also

as.data.frame.snake_layout() for the tables of the returned layout; survey_sequence() and sequential_dist() for stacked bars; snake_palette() for level colors; ema_emotions, student_survey and ema_beeps for example data.

Examples

# Raw responses: 280 students, ten emotion items rated 1-5
survey_snake(ema_emotions, sort_by = "mean")

# Correlations between adjacent items on the U-turns
survey_snake(ema_emotions, arc_fill = "correlation", tick_shape = "dot")

# Experience sampling: one band per study day, responses at their time
survey_snake(ema_beeps, var = "happy", day = "day",
             timestamp = "start_time")

# A table of counts with named levels
counts <- matrix(c(110, 210, 79,  84, 42,
                   126, 205, 68, 100, 26,
                   184, 226, 47,  58, 10),
                 nrow = 3, byrow = TRUE,
                 dimnames = list(c("LOC1", "LOC2", "LOC3"),
                                 c("Never", "Rarely", "Sometimes",
                                   "Often", "Always")))
survey_snake(counts, tick_shape = "bar",
             colors = snake_palette("earth", n = 5))

# One panel per group of items
survey_snake(student_survey, facet = TRUE, tick_shape = "bar")


Plot a timeline of phases as a serpentine of monthly blocks

Description

timeline_snake() draws a timeline snake plot, which shows a succession of phases, such as the positions held in a career or the stages of a project, as colored blocks folded into bands joined by U-turns. With dated input each block is one month, so the length of a phase is proportional to its duration and a span of many years fits in one panel while its order is kept.

The function takes a data frame with one row per phase (state, start date, end date) and builds the monthly sequence. It labels each change of phase with its start month, labels each band with the year at its middle, and prints the state names inside the phases. A vector of states, one per time unit, is drawn as given. Colors default to a light-to-dark blue ramp in phase order. The drawing is done by sequence_snake(), and its display options can be passed here. The plot is drawn on the current device and NULL is returned invisibly.

For an undated sequence of many short events use sequence_snake(); for many sequences use multi_snake().

Usage

timeline_snake(
  sequence,
  states = NULL,
  colors = NULL,
  rows = NULL,
  band_height = 28,
  band_gap = 30,
  plot_width = 500,
  margin = c(top = 35, right = 10, bottom = 65, left = 20),
  orientation = "horizontal",
  start_from = "left",
  flow = c("natural", "snake"),
  show_labels = FALSE,
  show_legend = TRUE,
  show_numbers = FALSE,
  show_state = TRUE,
  state_size = 1,
  show_ticks = FALSE,
  tick_labels = NULL,
  transition_labels = NULL,
  transition_pos = NULL,
  tick_color = "#444444",
  tick_length = 6,
  tick_size = 0.8,
  border_color = NA,
  block_labels = NULL,
  band_labels = NULL,
  title = NULL,
  background = "white",
  shadow = TRUE,
  text_size = 0.5,
  legend_text_size = 1.2
)

Arguments

sequence

Phases as a data frame whose first three columns are the state, the start date and the end date, one row per phase. Dates may be "YYYY-MM", "YYYY-MM-DD", other common date formats, or Date values; start and end months are both included. Alternatively a vector of states, one per time unit.

states

State labels in legend order. NULL (default) takes them in order of first appearance. Every state in sequence must be listed.

colors

State colors: a vector named by state, or an unnamed vector recycled over the states. NULL (default) uses a light-to-dark blue ramp over the states in order.

rows

Number of bands. NULL (default) uses about 20 months per band and at least two bands for data frame input, and one band per 11 positions for vector input.

band_height

Height of each band in plot units (default 28).

band_gap

Gap between bands in plot units (default 30, which leaves room for the year labels).

plot_width

Length of each band in plot units (default 500).

margin

Named numeric vector of top, right, bottom and left margins in plot units (default c(top = 35, right = 10, bottom = 65, left = 20)).

orientation

"horizontal" (default). "vertical" turns the bands into columns but places the blocks across each column rather than along it, so the horizontal layout is recommended.

start_from

Side on which the first band starts: "left" (default) or "right".

flow

"natural" (default): every band reads in the same direction, like lines of text. "snake": bands alternate direction, so the sequence runs on through each U-turn.

show_labels

Label each band with the range of positions it holds (default FALSE).

show_legend

Draw the state legend (default TRUE).

show_numbers

Print each block's position inside it (default FALSE).

show_state

Print the state name inside each phase (default TRUE).

state_size

Text size of the state names (default 1).

show_ticks

Draw ruler ticks at block boundaries, outside the bands (default FALSE).

tick_labels

Labels for evenly spaced ruler marks on every band, such as month.abb. Setting them turns on show_ticks.

transition_labels

Labels for the points where the state changes, in order. NULL (default) uses, for data frame input, the start month of each phase after the first, such as "Jun 2020".

transition_pos

Positions of transition_labels along the sequence, in blocks; fractions such as 6.5 are allowed. NULL (default) places the labels at the changes of state.

tick_color

Color of ticks and of band and transition labels (default "#444444").

tick_length

Length of ticks in plot units (default 6).

tick_size

Text size of tick, band and transition labels (default 0.8).

border_color

Color of block outlines, or NA (default) for none.

block_labels

Labels for the blocks, one per position. They replace the position numbers, and are drawn below the blocks when ruler ticks are shown.

band_labels

One label per band (length rows). NULL (default) uses, for data frame input, the year at the middle of each band.

title

Plot title, or NULL (default) for none.

background

Background color (default "white").

shadow

Draw drop shadows (default TRUE).

text_size

Text size of block numbers and block labels (default 0.5).

legend_text_size

Size of the legend text (default 1.2).

Value

The plot is drawn on the current device; the function returns NULL invisibly.

See Also

sequence_snake(), which draws the plot; multi_snake() for many sequences; activity_snake() for events within days.

Examples

# An academic career, one row per position
career <- data.frame(
  role  = c("PhD student", "Postdoc", "Lecturer", "Senior lecturer"),
  start = c("2012-09", "2016-10", "2019-01", "2023-08"),
  end   = c("2016-09", "2018-12", "2023-07", "2025-12")
)
timeline_snake(career)

# The same kind of display from a vector, one element per year
schooling <- rep(c("School", "Bachelor", "Master", "Work"),
                 times = c(12, 3, 2, 8))
timeline_snake(schooling, rows = 3)