biopsykit.protocols.base module

Module implementing a base class to represent psychological protocols.

class biopsykit.protocols.base.BaseProtocol(name, structure=None, test_times=None, **kwargs)[source]

Bases: object

Class representing a base class for psychological protocols and data collected within a study.

The general structure of the protocol can be specified by passing a structure dict to the constructor of BaseProtocol.

Up to three nested structure levels are supported:

  • 1st level: study part: Different parts of the study, such as: “Preface”, “Test”, and “Questionnaires”

  • 2nd level: phase: Different phases of the psychological protocol that belong to the same study part, such as: “Preparation”, “Stress”, “Recovery”

  • 3rd level: subphase: Different subphases that belong to the same phase, such as: “Baseline”, “Arithmetic Task”, “Feedback”

Note

Duration of phases and/or subphases are expected in seconds.

Parameters
  • name (str) – name of protocol

  • structure (dict, optional) –

    nested dictionary specifying the structure of the protocol. Up to three nested structure levels are supported:

    • 1st level: study_part: Different parts of the study, such as: “Preface”, “Test”, and “Questionnaires”

    • 2nd level: phase: Different phases of the psychological protocol that belong to the same study part, such as: “Preparation”, “Stress”, “Recovery”

    • 3rd level: subphase: Different subphases that belong to the same phase, such as: “Baseline”, “Arithmetic Task”, “Feedback”

    If a study part has no division into finer phases (or a phase has no division into finer subphases) the dictionary value can be set to None. If the whole study has no division into different parts, the structure dict can be set to None. Default: None

  • test_times (list, optional) – start and end time of psychological test (in minutes) or None if the protocol has no particular test. test_times is then internally set to [0, 0]. Default: None

  • **kwargs

    additional parameters to be passed to BaseProtocol, such as:

Examples

>>> from biopsykit.protocols import BaseProtocol
>>> # Example 1: study with three parts, no finer division into phases
>>> structure = {
>>>     "Preface": None,
>>>     "Test": None,
>>>     "Questionnaires": None
>>> }
>>> BaseProtocol(name="Base", structure=structure)
>>> # Example 2: study with three parts, all parts have different phases with specific durations
>>> structure = {
>>>     "Preface": {"Questionnaires": 240, "Baseline": 60},
>>>     "Test": {"Preparation": 120, "Test": 240, "Recovery": 120},
>>>     "Recovery": {"Part1": 240, "Part2": 240}
>>> }
>>> BaseProtocol(name="Base", structure=structure)
>>> # Example 3: only certain study parts have different phases (example: TSST)
>>> structure = {
>>>     "Before": None,
>>>     "TSST": {"Preparation": 300, "Talk": 300, "Math": 300},
>>>     "After": None
>>> }
>>> BaseProtocol(name="Base", structure=structure)
>>> # Example 4: study with phases and subphases, only certain study parts have different phases (example: MIST)
>>> structure = {
>>>     "Before": None,
>>>     "MIST": {
>>>         "MIST1": {"BL": 60, "AT": 240, "FB": 120},
>>>         "MIST2": {"BL": 60, "AT": 240, "FB": 120},
>>>         "MIST3": {"BL": 60, "AT": 240, "FB": 120}
>>>     },
>>>     "After": None
>>> }
>>> BaseProtocol(name="Base", structure=structure)
name: str

Study or protocol name

structure: Dict[str, Any]

Structure of protocol, i.e., whether protocol is divided into different parts, phases, or subphases.

If protocol is not divided into different parts protocol_structure is set to None.

saliva_types: Sequence[str]

List of saliva data types present in the study.

test_times: Sequence[int]

Start and end time of psychological test (in minutes).

If no psychological test was performed in the protocol test_times is set to [0, 0].

sample_times: Dict[str, Sequence[int]]

Dictionary with sample times of saliva samples (in minutes).

Sample times are either provided explicitly using the sample_times parameter in add_saliva_data() or by extracting it from the saliva data (if a time column is present).

saliva_data: Dict[str, Union[biopsykit.utils.datatype_helper._BiomarkerRawDataFrame, pandas.core.frame.DataFrame]]

Dictionary with saliva data collected during the study.

Data in SalivaRawDataFrame format can be added using add_saliva_data().

hr_data: Dict[str, Union[Dict[str, Dict[str, Union[biopsykit.utils.datatype_helper._HeartRateDataFrame, pandas.core.frame.DataFrame]]], Dict[str, Dict[str, Dict[str, Union[biopsykit.utils.datatype_helper._HeartRateDataFrame, pandas.core.frame.DataFrame]]]]]]

Dictionary with heart rate data collected during the study. If the study consists of multiple study parts each part has its own HeartRateSubjectDataDict. If the study has no individual study parts (only different phases), the name of the one and only study part defaults to Study (to ensure consistent dictionary structure).

Data in HeartRateSubjectDataDict format can be added using add_hr_data().

rpeak_data: Dict[str, Dict[str, Dict[str, pandas.core.frame.DataFrame]]]

Dictionary with R peak data collected during the study. If the study consists of multiple study parts each part has its own SubjectDataDict. If the study has no individual study parts (only different phases), the name of the one and only study part defaults to Study (to ensure consistent dictionary structure).

Data in SubjectDataDict format can be added using add_hr_data().

hr_results: Dict[str, pandas.core.frame.DataFrame]

Dictionary with heart rate results.

Dict keys are the identifiers that are specified when computing results from hr_data using compute_hr_results().

hr_above_baseline_results: Dict[str, pandas.core.frame.DataFrame]

Dictionary with heart rate above baseline results.

Dict keys are the identifiers that are specified when computing results from hr_data using compute_hr_above_baseline().

hrv_results: Dict[str, pandas.core.frame.DataFrame]

Dictionary with heart rate variability ensemble.

Dict keys are the identifiers that are specified when computing ensemble from rpeak_data using compute_hrv_results().

hrv_above_baseline_results: Dict[str, pandas.core.frame.DataFrame]

Dictionary with heart rate variability above baseline results.

Dict keys are the identifiers that are specified when computing results from rpeak_data using compute_hrv_above_baseline().

hr_ensemble: Dict[str, Dict[str, pandas.core.frame.DataFrame]]

Dictionary with merged heart rate data for heart rate ensemble plot.

Dict keys are the identifiers that are specified when computing ensemble HR data from hr_data using compute_hr_ensemble().

See also

hr_ensemble_plot()

heart rate ensemble plot

saliva_plot_params: Dict[str, Any]

Plot parameters for customizing the general saliva plot for a specific psychological protocol.

See also

saliva_plot()

saliva plot

hr_mean_plot_params: Dict[str, Any]

Plot parameters for customizing the general HR mean plot for a specific psychological protocol.

See also

hr_mean_plot()

HR mean plot

hr_ensemble_plot_params: Dict[str, Any]

Plot parameters for customizing the general HR ensemble plot for a specific psychological protocol.

See also

hr_ensemble_plot()

HR ensemble plot

to_file(file_path)[source]

Serialize Protocol object and export as file.

This function converts the basic information of this object (name, structure, test_times) to a JSON object and saves the serialized object to a JSON file.

Parameters

file_path (Path or str) – file path to export

classmethod from_file(file_path)[source]

Load serialized Protocol object from file.

Parameters

file_path (Path or str) – file path to export

Returns

Protocol instance

Return type

instance of BaseProtocol

add_saliva_data(saliva_data, saliva_type=None, sample_times=None, test_times=None, sample_times_absolute=False)[source]

Add saliva data collected during psychological protocol to Protocol instance.

Parameters
  • saliva_data (SalivaRawDataFrame or dict) – saliva data (or dict of such) to be added to this protocol.

  • saliva_type (str or list of str, optional) – saliva type (or list of such) of saliva data. Not needed if saliva_data is a dictionary, then the saliva types are inferred from the dictionary keys.

  • sample_times (list of int or dict, optional) – list of sample times in minutes. Sample times are either expected to be provided relative to the psychological test in the protocol (if present) or as absolute sample times. If passed as relative sample times (sample_times_absolute'' is ``False), a sample collected directly before the test should, per convention, be denoted as \(t = -1\) while a sample collected directly after the test was collected at time point :math`t = 0`.

  • test_times (list of int, optional) – list with start and end time of psychological test in minutes. Per convention, the start of the test should be at time point \(t = 0\). test_times is also used to compute the absolute sample times

  • sample_times_absolute (bool, optional) – True if sample times are provided as absolute time points or False if sample times are provided as relative time points to the psychological test. Default: False

add_hr_data(hr_data, rpeak_data=None, study_part=None)[source]

Add time-series heart rate data collected during psychological protocol to Protocol instance.

Parameters
  • hr_data (HeartRateSubjectDataDict) – dictionary with heart rate data of all subjects collected during the protocol.

  • rpeak_data (SubjectDataDict, optional) – dictionary with rpeak data of all subjects collected during the protocol. Needed if heart rate variability should be computed.

  • study_part (str, optional) – string indicating to which study part data belongs to or None if data has no individual study parts. Default: None

compute_hr_results(result_id, study_part=None, resample_sec=True, normalize_to=False, select_phases=False, split_into_subphases=False, mean_per_subject=True, add_conditions=False, reindex=False, params=None)[source]

Compute heart rate data results from one study part.

The different processing steps can be enabled or disabled by setting the function parameters to True or False, respectively. Parameters that are required for a specific processing step can be provided in the params dict. The dict key must match the name of the processing step.

Parameters
  • result_id (str) – Result ID, a descriptive name of the results that were computed. This ID will also be used as key to store the computed results in the hr_results dictionary.

  • study_part (str, optional) – study part the data which should be processed belongs to or None if data has no individual study parts. Default: None

  • resample_sec (bool, optional) – True to apply resampling. Instantaneous heart rate data will then be resampled to 1 Hz. Default: True

  • normalize_to (bool, optional) – True to normalize heart rate data per subject. Data will then be the heart rate increase relative to the average heart rate in the phase. The name of the phase (or a dataframe containing heart rate data to normalize to) is specified in the params dictionary (key: normalize_to). Default: False

  • select_phases (bool, optional) – True to only select specific phases for further processing, False to use all data from study_part. The phases to be selected are specified in the params dictionary (key: select_phases). Default: False

  • split_into_subphases (bool, optional) – True to further split phases into subphases, False otherwise. The subphases are provided as dictionary (keys: subphase names, values: subphase durations in seconds) in the params dictionary (key: split_into_subphases). Default: False

  • mean_per_subject (bool, optional) – True to compute the mean heart rate per phase (and subphase, if present) for each subject and combine results into one dataframe. The resulting index level names of the dataframe can be provided as list in the params dictionary (key: mean_per_subject). By default, the index level names are [“subject”, “phase”]. Default: True

  • add_conditions (bool, optional) – True to add subject conditions to dataframe data. Information on which subject belongs to which condition can be provided as SubjectConditionDataFrame or SubjectConditionDict in the params dictionary (key: add_conditions). Default: False

  • reindex (bool, optional) – True to reindex index levels of the resulting dataframe. Reindex index levels can be provided in the params dictionary as a dictionary with index levels as keys and index orders as values (key: reindex). Default: False

  • params (dict, optional) – dictionary with parameters provided to the different processing steps

compute_hrv_results(result_id, study_part=None, select_phases=False, split_into_subphases=False, dict_levels=None, hrv_params=None, add_conditions=False, params=None)[source]

Compute heart rate variability ensemble from one study part.

The different processing steps can be enabled or disabled by setting the function parameters to True or False, respectively. Parameters that are required for a specific processing step can be provided in the params dict. The dict key must match the name of the processing step.

Parameters
  • result_id (str) – Result ID, a descriptive name of the ensemble that were computed. This ID will also be used as key to store the computed ensemble in the hrv_results dictionary.

  • study_part (str, optional) – study part the data which should be processed belongs to or None if data has no individual study parts. Default: None

  • select_phases (bool, optional) – True to only select specific phases for further processing, False to use all data from study_part. The phases to be selected are specified in the params dictionary (key: select_phases). Default: False

  • split_into_subphases (bool, optional) – True to further split phases into subphases, False otherwise. The subphases are provided as dictionary (keys: subphase names, values: subphase durations in seconds) in the params dictionary (key: split_into_subphases). Default: False

  • dict_levels (list, optional) – list with names of dictionary levels which will also be the index level names of the resulting dataframe or None to use default level names: [“subject”, “phase”] (if split_into_subphases is False) or [“subject”, “phase”, “subphase”] (if split_into_subphases is True).

  • hrv_params (dict, optional) – dictionary with parameters to configure HRV processing or None to use default parameter. See hrv_process() for an overview on available parameters.

  • add_conditions (bool, optional) – True to add subject conditions to dataframe data. Information on which subject belongs to which condition can be provided as SubjectConditionDataFrame or SubjectConditionDict in the params dictionary (key: add_conditions). Default: False

  • params (dict, optional) – dictionary with parameters provided to the different processing steps.

compute_hr_ensemble(ensemble_id, study_part=None, resample_sec=True, normalize_to=True, select_phases=False, cut_phases=True, merge_dict=True, add_conditions=False, params=None)[source]

Compute heart rate ensemble data from one study part.

Heart rate ensemble data are time-series data where data from all subjects within one phase have the same length and can thus be overlaid as mean ± standard error in a plot.

The different processing steps can be enabled or disabled by setting the function parameters to True or False, respectively. Parameters that are required for a specific processing step can be provided in the params dict. The dict key must match the name of the processing step.

Parameters
  • ensemble_id (str) – ensemble identifier, a descriptive name of the ensemble data that were computed. This ID will also be used as key to store the computed ensemble data in the hr_ensemble dictionary.

  • study_part (str, optional) – study part the data which should be processed belongs to or None if data has no individual study parts. Default: None

  • resample_sec (bool, optional) – True to apply resampling. Instantaneous heart rate data will then be resampled to 1 Hz. Default: True

  • normalize_to (bool, optional) – True to normalize heart rate data per subject. Data will then be the heart rate increase relative to the average heart rate in the phase. The name of the phase (or a dataframe containing heart rate data to normalize to) is specified in the params dictionary (key: normalize_to). Default: False

  • select_phases (bool, optional) – True to only select specific phases for further processing, False to use all data from study_part. The phases to be selected are specified in the params dictionary (key: select_phases). Default: False

  • cut_phases (bool, optional) – True to cut time-series data to shortest duration of a subject in each phase, False otherwise. Default: True

  • merge_dict (bool, optional) – True to convert StudyDataDict into MergedStudyDataDict, i.e., merge dictionary data from individual subjects into one dataframe for each phase. Default: True

  • add_conditions (bool, optional) – True to add subject conditions to dataframe data. Information on which subject belongs to which condition can be provided as SubjectConditionDataFrame or SubjectConditionDict in the params dictionary (key: add_conditions). Default: False

  • params (dict, optional) – dictionary with parameters provided to the different processing steps

See also

hr_ensemble_plot()

Heart rate ensemble plot

compute_hr_above_baseline(result_id, baseline_phase, study_part=None, select_phases=False, split_into_subphases=False, add_conditions=False, params=None)[source]

Compute the relative amount of heart rate above a specified baseline.

The different processing steps can be enabled or disabled by setting the function parameters to True or False, respectively. Parameters that are required for a specific processing step can be provided in the params dict. The dict key must match the name of the processing step.

Parameters
  • result_id (str) – Result ID, a descriptive name of the results that were computed. This ID will also be used as key to store the computed results in the hr_above_baseline_results dictionary.

  • baseline_phase (str) – string indicating the name of the phase that should be used as baseline for computing the relative amount above the baseline.

  • study_part (str, optional) – study part the data which should be processed belongs to or None if data has no individual study parts. Default: None

  • select_phases (bool, optional) – True to only select specific phases for further processing, False to use all data from study_part. The phases to be selected are specified in the params dictionary (key: select_phases). Default: False

  • split_into_subphases (bool, optional) – True to further split phases into subphases, False otherwise. The subphases are provided as dictionary (keys: subphase names, values: subphase durations in seconds) in the params dictionary (key: split_into_subphases). Default: False

  • add_conditions (bool, optional) – True to add subject conditions to dataframe data. Information on which subject belongs to which condition can be provided as SubjectConditionDataFrame or SubjectConditionDict in the params dictionary (key: add_conditions). Default: False

  • params (dict, optional) – dictionary with parameters provided to the different processing steps

compute_hrv_above_baseline(result_id, baseline_phase, continuous_hrv_data, select_phases=False, split_into_subphases=False, add_conditions=False, hrv_columns=None, params=None)[source]

Compute the relative amount of heart rate variability above a specified baseline.

The different processing steps can be enabled or disabled by setting the function parameters to True or False, respectively. Parameters that are required for a specific processing step can be provided in the params dict. The dict key must match the name of the processing step.

Parameters
  • result_id (str) – Result ID, a descriptive name of the results that were computed. This ID will also be used as key to store the computed results in the hrv_above_baseline_results dictionary.

  • baseline_phase (str) – string indicating the name of the phase that should be used as baseline for computing the relative amount above the baseline.

  • continuous_hrv_data (SubjectDataDict) – dictionary with continuous HRV of all subjects collected during the protocol.

  • select_phases (bool, optional) – True to only select specific phases for further processing, False to use all data from study_part. The phases to be selected are specified in the params dictionary (key: select_phases). Default: False

  • split_into_subphases (bool, optional) – True to further split phases into subphases, False otherwise. The subphases are provided as dictionary (keys: subphase names, values: subphase durations in seconds) in the params dictionary (key: split_into_subphases). Default: False

  • add_conditions (bool, optional) – True to add subject conditions to dataframe data. Information on which subject belongs to which condition can be provided as SubjectConditionDataFrame or SubjectConditionDict in the params dictionary (key: add_conditions). Default: False

  • hrv_columns (list of str) – selected column names for computing or None to compute relative amount above baseline for all columns. Default: None

  • params (dict, optional) – dictionary with parameters provided to the different processing steps

add_hr_results(result_id, results)[source]

Add existing heart rate processing ensemble.

Parameters
  • result_id (str) – identifier of result parameters used to store dataframe in hr_results dictionary.

  • results (DataFrame) – dataframe with computed heart rate processing ensemble

get_hr_results(result_id)[source]

Return heart rate processing results.

Heart rate results can be computed by calling compute_hr_results().

Parameters

result_id (str) – identifier of result parameters specified when computing results via compute_hr_results()

Returns

heart rate processing results

Return type

DataFrame

add_hrv_results(result_id, results)[source]

Add existing heart rate variability processing ensemble.

Parameters
  • result_id (str) – identifier of result parameters used to store dataframe in hrv_results dictionary

  • results (DataFrame) – dataframe with computed heart rate variability processing ensemble

export_hr_results(base_path, prefix=None)[source]

Export all heart rate results to csv files.

Parameters
  • base_path (Path or str) – folder path to export all heart rate result files to

  • prefix (str, optional) – prefix to add to file name or None to use name attribute (in lowercase) as prefix

export_hr_above_baseline_results(base_path, prefix=None)[source]

Export all heart rate above baseline results to csv files.

Parameters
  • base_path (Path or str) – folder path to export all heart rate above baseline result files to

  • prefix (str, optional) – prefix to add to file name or None to use name attribute (in lowercase) as prefix

export_hr_ensemble(base_path, prefix=None)[source]

Export all heart rate ensemble data to Excel files.

Parameters
  • base_path (Path or str) – folder path to export all heart rate ensemble files to

  • prefix (str, optional) – prefix to add to file name or None to use name attribute (in lowercase) as prefix

export_hrv_results(base_path, prefix=None)[source]

Export all heart rate variability results to csv files.

Parameters
  • base_path (Path or str) – folder path to export all heart rate variability result files to

  • prefix (str, optional) – prefix to add to file name or None to use name attribute (in lowercase) as prefix

export_hrv_above_baseline_results(base_path, prefix=None)[source]

Export all heart rate variability above baseline results to csv files.

Parameters
  • base_path (Path or str) – folder path to export all heart rate variability above baseline result files to

  • prefix (str, optional) – prefix to add to file name or None to use name attribute (in lowercase) as prefix

get_hrv_results(result_id)[source]

Return heart rate variability processing ensemble.

Heart rate variability ensemble can be computed by calling compute_hrv_results().

Parameters

result_id (str) – identifier of result parameters specified when computing ensemble via compute_hrv_results()

Returns

heart rate variability processing ensemble

Return type

DataFrame

add_hr_ensemble(ensemble_id, ensemble)[source]

Add existing heart rate ensemble data.

Parameters
  • ensemble_id (str) – identifier of ensemble parameters used to store dictionary in hr_ensemble dictionary

  • ensemble (MergedStudyDataDict) – ensemble data as MergedStudyDataDict

get_hr_ensemble(ensemble_id)[source]

Return heart rate ensemble data.

Parameters

ensemble_id (str) – identifier of ensemble parameters specified when computing ensemble parameters via compute_hr_ensemble()

Returns

heart rate ensemble ensemble

Return type

DataFrame

saliva_plot(saliva_type='cortisol', **kwargs)[source]

Plot saliva data during psychological protocol as mean ± standard error.

Parameters
  • saliva_type ({"cortisol", "amylase", "il6"}, optional) – saliva type to be plotted. If a dict is passed and saliva_type is None the saliva types are inferred from dict keys. Default: cortisol

  • **kwargs – additional parameters to be passed to saliva_plot().

Returns

Return type

Optional[Tuple[matplotlib.figure.Figure, matplotlib.axes._axes.Axes]]

See also

saliva_plot()

Plot saliva data during a psychological protocol

static saliva_plot_combine_legend(fig, ax, saliva_types, **kwargs)[source]

Combine multiple legends of saliva_plot() into one legend outside plot.

If data from multiple saliva types are combined into one plot (e.g., by calling saliva_plot() on the same plot twice) then two separate legend are created. This function can be used to combine the two legends into one.

Parameters
  • fig (Figure) – figure object

  • ax (Axes) – axes object

  • saliva_types (list) – list of saliva types in plot

  • **kwargs – additional arguments to customize plot that are passed to saliva_plot_combine_legend()

saliva_feature_boxplot(x, saliva_type, feature=None, stats_kwargs=None, **kwargs)[source]

Draw a boxplot with significance brackets, specifically designed for saliva features.

This is a wrapper of saliva_feature_boxplot() that directly uses the saliva data added to this Protocol instance.

Parameters
  • x (str) – column of x axis in data

  • saliva_type (str) – type of saliva data to plot

  • feature (str, optional) – name of feature to plot or None

  • stats_kwargs (dict, optional) – dictionary with arguments for significance brackets

  • **kwargs – additional arguments that are passed to saliva_feature_boxplot()

Returns

Return type

Tuple[matplotlib.figure.Figure, matplotlib.axes._axes.Axes]

See also

saliva_feature_boxplot()

plot saliva features as boxplot without Protocol instance

feature_boxplot()

plot features as boxplot

static saliva_multi_feature_boxplot(data, saliva_type, features, hue=None, stats_kwargs=None, **kwargs)[source]

Draw multiple features as boxplots with significance brackets, specifically designed for saliva features.

This is a wrapper of saliva_multi_feature_boxplot().

Parameters
  • data (SalivaFeatureDataFrame) – saliva feature dataframe

  • saliva_type (str) – type of saliva data to plot

  • hue (str, optional) – column name of grouping variable. Default: None

  • features (list of str or dict of str) – features to plot. If features is a list, each entry must correspond to one feature category in the index level specified by group. A separate subplot will be created for each feature. If similar features (i.e., different slope or AUC parameters) should be combined into one subplot, features can be provided as dictionary. Then, the dict keys specify the feature category (a separate subplot will be created for each category) and the dict values specify the feature (or list of features) that are combined into the subplots.

  • stats_kwargs (dict, optional) – nested dictionary with arguments for significance brackets. See feature_boxplot() for further information

Returns

Return type

Tuple[matplotlib.figure.Figure, Iterable[matplotlib.axes._axes.Axes]]

See also

saliva_multi_feature_boxplot()

plot multiple saliva features as boxplots without instantiating a Protocol instance

StatsPipeline()

class to create statistical analysis pipelines and get parameter for plotting significance brackets

hr_ensemble_plot(ensemble_id, subphases=None, **kwargs)[source]

Draw heart rate ensemble plot.

Parameters
  • ensemble_id (str) – identifier of the ensemble data to be plotted. Ensemble data needs to be computed using compute_hr_ensemble() first

  • subphases (dict, optional) – dictionary with phases (keys) and subphases (values - dict with subphase names and subphase durations) or None if no subphases are present. Default: None

  • **kwargs (dict, optional) –

    additional parameters to be passed to hr_ensemble_plot() for plot configuration, such as:

    • ax: pre-existing axes for the plot. Otherwise, a new figure and axes object is created and returned.

    • palette: color palette to plot data from different phases. If palette is a str then it is assumed to be the name of a fau_colors palette (fau_colors.cmaps._fields).

    • figsize: tuple specifying figure dimensions

    • ensemble_alpha: transparency value for ensemble plot errorband (around mean). Default: 0.3

    • background_alpha: transparency value for background spans (if subphases are present). Default: 0.2

    • linestyle: list of line styles for ensemble plots. Must match the number of phases to plot

    • phase_text: string pattern to customize phase name shown in legend with placeholder for subphase name. Default: “{}”

    To style axes:

    • is_relative: boolean indicating whether heart rate data is relative (in % relative to baseline) or absolute (in bpm). Default: True

    • xlabel: label of x axis. Default: “\(Time [s]\)

    • xaxis_minor_tick_locator: locator object to style x axis minor ticks. Default: 60 sec

    • ylabel: label of y axis. Default: “\(\Delta HR [\%]\)

    • ylims: y axis limits. Default: None to automatically infer limits

    To style the annotations at the end of each phase:

    • end_phase_text: string pattern to customize text at the end of phase with placeholder for phase name. Default: “{}”

    • end_phase_line_color: line color of vertical lines used to indicate end of phase. Default: “#e0e0e0”

    • end_phase_line_width: line width of vertical lines used to indicate end of phase. Default: 2.0

    To style legend:

    • legend_loc: location of legend. Default: “lower right”

    • legend_bbox_to_anchor: box that is used to position the legend in conjunction with legend_loc

Returns

Return type

Tuple[matplotlib.figure.Figure, matplotlib.axes._axes.Axes]

See also

compute_hr_ensemble()

compute heart rate ensemble data

hr_ensemble_plot()

Heart rate ensemble plot

hr_mean_plot(result_id, **kwargs)[source]

Plot course of heart rate as mean ± standard error over phases (and subphases) of a psychological protocol.

The correct plot is automatically inferred from the provided data:

  • only phase index level: plot phases over x axis

  • phase and subphase index levels: plot subphases over x axis, highlight phases as vertical spans

  • additionally: condition level: plot data of different conditions individually (corresponds to hue parameter in biopsykit.plotting.lineplot())

Parameters
  • result_id (str) – identifier of the heart rate result data to be plotted

  • **kwargs

    additional parameters to be passed to hr_mean_plot() for plot configuration, such as:

    • ax: pre-existing axes for the plot. Otherwise, a new figure and axes object is created and returned.

    • figsize: tuple specifying figure dimensions

    • palette: color palette to plot data from different conditions. If palette is a str then it is assumed to be the name of a fau_colors palette (fau_colors.cmaps._fields).

    • is_relative: boolean indicating whether heart rate data is relative (in % relative to baseline) or absolute (in bpm). Default: False

    • order: list specifying the order of categorical values (i.e., conditions) along the x axis.

    • x_offset: offset value to move different groups along the x axis for better visualization. Default: 0.05

    • xlabel: label of x axis. Default: “Subphases” (if subphases are present) or “Phases” (if only phases are present)

    • ylabel: label of y axis. Default: “\(\Delta HR [%]\)

    • ylims: list to manually specify y axis limits, float to specify y axis margin (see margin() for further information), or None to automatically infer y axis limits

    • marker: string or list of strings to specify marker style. If marker is a string, then marker of each line will have the same style. If marker is a list, then marker of each line will have a different style.

    • linestyle: string or list of strings to specify line style. If linestyle is a string, then each line will have the same style. If linestyle is a list, then each line will have a different style.

Returns

Return type

Tuple[matplotlib.figure.Figure, matplotlib.axes._axes.Axes]

See also

hr_mean_plot()

Plot heart rate data as lineplot with mean and standard error

lineplot()

Plot generic data as lineplot with mean and standard error