biopsykit.protocols.plotting module¶
Module providing some standard plots for visualizing data collected during a psychological protocol.
- biopsykit.protocols.plotting.hr_ensemble_plot(data, subphases=None, **kwargs)[source]¶
Draw a heart rate ensemble plot.
This function plots time-series heart rate continuously as ensemble plot (mean ± standard error). If the data consist of multiple phases, data from each phase are overlaid in the same plot. If each phase additionally consists of subphases, the single subphases are highlighted in the plot.
The input data is expected to be a
MergedStudyDataDict, i.e., a dictionary with merged time-series heart rate data, of multiple subjects, split into individual phases. Per phase, the data of each subjects have same length and are combined into one common dataframe.- Parameters
data (
MergedStudyDataDict) – dict with heart rate data to plotsubphases (dict, optional) – dictionary with phases (keys) and subphases (values - dict with subphase names and subphase durations) or
Noneif no subphases are present. Default:None**kwargs (dict, optional) –
optional arguments for plot configuration.
To style general plot appearance:
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 phasesensemble_alpha: transparency value for ensemble plot errorband (around mean). Default: 0.3background_alpha: transparency value for background spans (if subphases are present). Default: 0.2linestyle: list of line styles for ensemble plots. Must match the number of phases to plotphase_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:Truexlabel: label of x axis. Default: “\(Time [s]\)”xaxis_minor_tick_locator: locator object to style x axis minor ticks. Default: 60 secylabel: label of y axis. Default: “\(\Delta HR [\%]\)”ylims: y axis limits. Default:Noneto 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 withlegend_loc
- Returns
- Return type
tuple[matplotlib.figure.Figure, matplotlib.axes._axes.Axes] | None
See also
MergedStudyDataDictdictionary format
merge_study_data_dict()function to build
MergedStudyDataDict
Examples
>>> from biopsykit.protocols.plotting import hr_ensemble_plot >>> # Example with subphases >>> subphase_dict = { >>> "Phase1": {"Baseline": 60, "Stress": 120, "Recovery": 60}, >>> "Phase2": {"Baseline": 60, "Stress": 120, "Recovery": 60}, >>> "Phase3": {"Baseline": 60, "Stress": 120, "Recovery": 60} >>> } >>> fig, ax = hr_ensemble_plot(data=data, subphases=subphase_dict)
- biopsykit.protocols.plotting.hr_ensemble_plot_df(data, group_level, **kwargs)[source]¶
Draw a heart rate ensemble plot.
This function plots time-series heart rate continuously as ensemble plot (mean ± standard error). If the data consist of multiple phases, data from each phase are overlaid in the same plot. If each phase additionally consists of subphases, the single subphases are highlighted in the plot.
The input data is expected to be a
MergedStudyDataDict, i.e., a dictionary with merged time-series heart rate data, of multiple subjects, split into individual phases. Per phase, the data of each subjects have same length and are combined into one common dataframe.- Parameters
data (
MergedStudyDataDict) – dict with heart rate data to plotsubphases (dict, optional) – dictionary with phases (keys) and subphases (values - dict with subphase names and subphase durations) or
Noneif no subphases are present. Default:None**kwargs (dict, optional) –
optional arguments for plot configuration.
To style general plot appearance:
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 phasesensemble_alpha: transparency value for ensemble plot errorband (around mean). Default: 0.3background_alpha: transparency value for background spans (if subphases are present). Default: 0.2linestyle: list of line styles for ensemble plots. Must match the number of phases to plotphase_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:Truexlabel: label of x axis. Default: “\(Time [s]\)”xaxis_minor_tick_locator: locator object to style x axis minor ticks. Default: 60 secylabel: label of y axis. Default: “\(\Delta HR [\%]\)”ylims: y axis limits. Default:Noneto 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 withlegend_loc
group_level (str_t) –
- Returns
- Return type
tuple[matplotlib.figure.Figure, matplotlib.axes._axes.Axes] | None
See also
MergedStudyDataDictdictionary format
merge_study_data_dict()function to build
MergedStudyDataDict
Examples
>>> from biopsykit.protocols.plotting import hr_ensemble_plot >>> # Example with subphases >>> subphase_dict = { >>> "Phase1": {"Baseline": 60, "Stress": 120, "Recovery": 60}, >>> "Phase2": {"Baseline": 60, "Stress": 120, "Recovery": 60}, >>> "Phase3": {"Baseline": 60, "Stress": 120, "Recovery": 60} >>> } >>> fig, ax = hr_ensemble_plot(data=data, subphases=subphase_dict)
- biopsykit.protocols.plotting.hr_mean_plot(data, **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
phaseindex level: plot phases over x axisphaseandsubphaseindex levels: plot subphases over x axis, highlight phases as vertical spansadditionally:
conditionlevel: plot data of different conditions individually (corresponds tohueparameter inlineplot())
- Parameters
data (
MeanSeDataFrame) – Heart rate data to plot. Must be provided asMeanSeDataFramewith columnsmeanandsecomputed over phases (and, if available, subphases)**kwargs –
additional parameters to be passed to the plot, such as:
ax: pre-existing axes for the plot. Otherwise, a new figure and axes object is created and returned.figsize: tuple specifying figure dimensionspalette: color palette to plot data from different conditions. Ifpaletteis a str then it is assumed to be the name of afau_colorspalette (fau_colors.cmaps._fields).is_relative: boolean indicating whether heart rate data is relative (in % relative to baseline) or absolute (in bpm). Default:Falseorder: 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.05xlabel: 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 (seemargins()for further information), orNoneto automatically infer y axis limits.marker: string or list of strings to specify marker style. Ifmarkeris a string, then marker of each line will have the same style. Ifmarkeris a list, then marker of each line will have a different style.linestyle: string or list of strings to specify line style. Iflinestyleis a string, then each line will have the same style. Iflinestyleis a list, then each line will have a different style.
- Returns
- Return type
See also
lineplot()Plot data as lineplot with mean and standard error
- biopsykit.protocols.plotting.saliva_plot(data, saliva_type=None, sample_times=None, test_times=None, sample_times_absolute=False, remove_s0=False, **kwargs)[source]¶
Plot saliva data during psychological protocol as mean ± standard error.
The function accepts raw saliva data per subject (
SalivaRawDataFrame) as well as pre-computed mean and standard error values of saliva samples (SalivaMeanSeDataFrame). To combine data from multiple saliva types (maximum: 2) into one plot a dict can be passed todata.If a psychological test (e.g., TSST, MIST, or Stroop) was performed, the test time is highlighted as vertical span within the plot.
Note
If no sample times are provided (neither via
timecolumn indatanor viasample_timesparameter) thensampleswill be used as x axis- Parameters
data (
SalivaRawDataFrame, ) –SalivaMeanSeDataFrame, or dict of such Saliva data to plot. Must either be provided asSalivaRawDataFramewith raw saliva data per subject or asSalivaMeanSeDataFramewith columnsmeanandsecomputed per saliva sample. To plot data from multiple saliva types (maximum: 2) a dict can be passed (keys: saliva types, values: saliva data).saliva_type ({"cortisol", "amylase", "il6"}, optional) – saliva type to be plotted. If a dict is passed and
saliva_typeisNonethe saliva types are inferred from dict keys.sample_times (list or dict of lists) – sample times in minutes relative to psychological test or a dict of such if sample times are different for the individual saliva types.
test_times (list of int, optional) – start and end times of psychological test (in minutes) or
Noneif no test was performedsample_times_absolute (bool, optional) –
Trueif absolute sample times were provided (i.e., the duration of the psychological test was already added to the sample times),Falseif relative sample times were provided and absolute times should be computed based on test times specified bytest_times. Default:Falseremove_s0 (bool, optional) – whether to remove the first saliva sample for plotting or not. Default:
False**kwargs –
additional parameters to be passed to the plot.
To style general plot appearance:
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 phasesfigsize: tuple specifying figure dimensionsmarker: string or list of strings to specify marker style. Ifmarkeris a string, then the markers of each line will have the same style. Ifmarkeris a list, then the markers of each line will have a different style.linestyle: string or list of strings to specify line style. Iflinestyleis a string, then each line will have the same style. Iflinestyleis a list, then each line will have a different style.
To style axes:
x_offset: offset value to move different groups along the x axis for better visualization. Default: 0.05xlabel: 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 (seemargins()for further information), orNoneto automatically infer y axis limits.
To style the vertical span highlighting the psychological test in the plot:
test_title: title of testtest_fontsize: fontsize of the test title. Default: “medium”test_color: color of vspan. Default: #9e9e9etest_alpha: transparency value of vspan: Default: 0.5
- Returns
- Return type
tuple[matplotlib.figure.Figure, matplotlib.axes._axes.Axes] | None
See also
lineplot()Plot data as lineplot with mean and standard error
- biopsykit.protocols.plotting.saliva_plot_combine_legend(fig, ax, saliva_types, **kwargs)[source]¶
Combine multiple legends of
saliva_plotinto one joint legend outside of 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 objectax (
Axes) – axes objectsaliva_types (list) – list of saliva types in plot
**kwargs –
additional arguments to customize plot, such as:
legend_loc: Location of legend. Default:upper centerlegend_size: Legend size. Default:smallrect: Rectangle in normalized figure coordinates into which the whole subplots area (including labels) will fit. Used to conveniently place legend outside of figure.
- biopsykit.protocols.plotting.saliva_feature_boxplot(data, x, saliva_type, hue=None, feature=None, stats_kwargs=None, **kwargs)[source]¶
Draw a boxplot with significance brackets, specifically designed for saliva features.
This is a wrapper of
feature_boxplot()that can be used to plot saliva features and allows to easily add significance brackets that indicate statistical significance.Note
The input data is assumed to be in long-format.
- Parameters
data (
SalivaFeatureDataFrame) – data to plotx (str) – column of x axis in
datasaliva_type (str) – type of saliva data to plot
hue (str, optional) – column name of grouping variable. Default:
Nonefeature (str, optional) – name of feature to plot or
Nonestats_kwargs (dict, optional) – dictionary with arguments for significance brackets
**kwargs – additional arguments that are passed to
feature_boxplot()andboxplot()
- Returns
- Return type
See also
feature_boxplot()plot features as boxplot
StatsPipelineclass to create statistical analysis pipelines and get parameter for plotting significance brackets
- biopsykit.protocols.plotting.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
multi_feature_boxplot()that can be used to plot saliva features and allows to easily add significance brackets that indicate statistical significance.Note
The input data is assumed to be in long-format.
- Parameters
data (
SalivaFeatureDataFrame) – data to plotsaliva_type (str) – type of saliva data to plot
hue (str, optional) – column name of grouping variable. Default:
Nonefeatures (list of str or dict of str) – features to plot. If
featuresis a list, each entry must correspond to one feature category in the index level specified bygroup. 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,featurescan 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
fig (
Figure) – figure objectaxs (list of
matplotlib.axes.Axes) – list of subplot axes objects
- Return type
tuple[matplotlib.figure.Figure, collections.abc.Iterable[matplotlib.axes._axes.Axes]]
See also
multi_feature_boxplot()plot multiple features as boxplots
StatsPipelineclass to create statistical analysis pipelines and get parameter for plotting significance brackets