SimPlotNamespace#

class pypillometry.sim.SimPlotNamespace(data=None)[source]#

Bases: PlotNamespace

Plotting methods of a SimEyeData object (d.plot): those of PlotNamespace and plots of the data together with the ground truth.

Methods

plot_blink_clusters

Plot the detected blinks in groups of similar shape.

plot_blinks

Plot detected blinks in separate subplots.

plot_calibration

Plot spatial calibration data for one or more eyes in subplots.

plot_components

The true components of the latent pupil size (log-%, TimescalePupil).

plot_experimental_setup

Plot visualization of eye-tracking experimental setup geometry.

plot_heatmap

Plot EyeData as a heatmap.

plot_intervals

Plotting data around intervals.

plot_local_level

Plot the local level of the pupil (see local_level()) and the scales it comes from.

plot_masked

plot_pupil

Make a plot of the pupil data using matplotlib.

plot_pupil_covariate

Plot the pupil size against a channel in d.aux (e.g., the luminance of the scene video or the viewing distance).

plot_pupil_foreshortening_error_surface

Plot a heatmap showing average pupil size across x/y gaze positions.

plot_pupil_segments

Plot the whole dataset chunked up into segments (usually to a PDF file).

plot_pupil_spectrum

Plot the power spectrum of the pupil size on logarithmic axes.

plot_scanpath

Plot EyeData as a scanpath.

plot_task_events

The events of the task of a simulation (see Task): one lane per event label, stimuli as bars over their duration, responses as ticks, coloured by condition.

plot_timeseries

Plot a part of the data.

plot_timeseries_segments

Plot the whole dataset chunked up into segments (usually to a PDF file).

plot_truth

The pupil data with the true pupil: as measured without noise and, if they differ (e.g., by foreshortening), the true pupil size.

Details

Plot the detected blinks in groups of similar shape.

A quick check of blinks_detect(): if a group looks unlike blinks (e.g., no drop and rise, steps), the detection finds too much and its parameters should be changed.

Blinks with missing samples: the pupil before and after the missing samples (the core, from the first to the last missing sample) is cut out with window. Each part is shifted to 0 at its outer end (the first fifth of the time before the core, the last fifth of the time after it), and the blinks are clustered (Ward, on the parts and the log of the duration of the core). The tree is cut so that there are n_clusters groups with at least min_size of these blinks; the rest are shown together as “other”.

Blinks without missing samples (partial blinks, see blinks_detect_partial(): blinks that do not close the eye completely) are shown separately, all in one panel: the pupil in window around the middle of the blink, shifted to 0 at the start.

One row per eye: one panel per group (the largest first), one for “other” and one for the blinks without missing samples. The panels of the groups show all blinks with missing samples in light grey, the blinks of the group in color and their median in black; the time before the core is relative to its start, the time after it relative to its end, and the cores (of different durations) are the shaded gap. Below each panel, a histogram of the durations of the cores (the time the eye was closed) of the group, with the one of all blinks with missing samples as outline (both normalized; the last bin has all durations above the 99th percentile), and of the durations of the blinks without missing samples. The percentages are of all detected blinks of the eye.

Parameters:
  • eyes (str | list) – eyes to plot; if empty, all eyes with pupil data

  • window (float, str, Quantity or tuple) – time (before, after) the core, or the middle of a blink without missing samples (in ms, or with units)

  • n_clusters (int) – number of groups (besides “other”)

  • min_size (float) – minimum fraction of the blinks with missing samples in a group

  • figsize (tuple) – size of the figure; default: 4 x 4.5 inches per panel

  • title (str) – title of the figure

  • axes (sequence of Axes, optional) – axes to draw on, len(eyes) * (n_clusters + 2) (one row per eye); default: a new figure

  • seed (int, optional) – seed for the random subset of blinks that is clustered if there are more than 5000 (the others go to the nearest group)

Return type:

Figure

Raises:

ValueError – if the object has no pupil data or no detected blinks

Examples

>>> import pypillometry as pp
>>> d = pp.get_example_data("rlmw_002_short").pupil.blinks_detect()
>>> fig = d.plot.plot_blink_clusters(n_clusters=2)
../../_images/pypillometry-sim-SimPlotNamespace-1.png

Plot detected blinks in separate subplots.

Parameters:
  • eyes (str | list) – Eyes to plot

  • variables (str | list) – Variables to plot

  • pdf_file (str | None) – Save to PDF file if provided

  • nrow (int) – Number of rows per figure

  • ncol (int) – Number of columns per figure

  • figsize (tuple) – Figure size (width, height)

  • pre_blink (float) – Time before blink to include (in ms)

  • post_blink (float) – Time after blink to include (in ms)

  • units (str) – Display units for time axis; default “sec”

  • show_index (bool) – Show blink index numbers

Return type:

list[Figure]

Returns:

one figure per nrow x ncol blinks (also returned when pdf_file is given; the figures are then closed)

Raises:

ValueError – if the object has no data for variables

Examples

Check the detected blinks of the left eye (the numbers are the blink indices):

>>> import pypillometry as pp
>>> from pypillometry import u
>>> import matplotlib.pyplot as plt
>>> d = pp.get_example_data("rlmw_002_short")
>>> d = d.pupil.blinks_detect()
>>> figs = d.plot.plot_blinks(eyes="left", nrow=3, ncol=5, figsize=(12, 6),
...                           units="sec")
../../_images/pypillometry-sim-SimPlotNamespace-2.png
plot_calibration(eyes=None, show_surface=True, interpolation='rbf', title=None, axes=None, figsize=None)#

Plot spatial calibration data for one or more eyes in subplots.

Plots each eye in a separate subplot with the plot() method of its SpatialCalibration object: calibration accuracy with target points (black X), measured points (dark blue +), and optional interpolated error surface.

Parameters:
  • eyes (Union[str, list, None]) – Which eye(s) to plot. If None or empty list, plots all available eyes. Can be a single eye name (e.g., ‘left’) or list of eye names (e.g., [‘left’, ‘right’]).

  • show_surface (bool) – If True, show interpolated error surface as background. If False, show only the calibration points.

  • interpolation (str) – Interpolation method for surface (only used if show_surface=True). Options: ‘rbf’, ‘linear’, ‘cubic’, ‘nearest’

  • title (str) – title of the figure

  • axes (list of matplotlib.axes.Axes, optional) – axes to plot on, one per eye; default: a new figure (one subplot per eye, side by side)

  • figsize (tuple) – size of the new figure; default: 10 x 8 inches per eye

Return type:

Figure

Returns:

the figure of the plot

Raises:

ValueError – If no calibration data is available, or if axes does not contain one axes per eye

Examples

>>> import pypillometry as pp
>>> data = pp.EyeData.from_eyelink('data.edf')
>>> # Plot all eyes with surface
>>> fig = data.plot.plot_calibration()
>>> 
>>> # Plot only left eye without surface
>>> fig = data.plot.plot_calibration(eyes='left', show_surface=False)
>>> 
>>> # Plot specific eyes
>>> fig = data.plot.plot_calibration(eyes=['left', 'right'])
plot_components(eye=None, plot_range=None, units='sec', axes=None, figsize=(12, 7))[source]#

The true components of the latent pupil size (log-%, TimescalePupil).

Three panels: the latent signal with its slow part; the fast component (and the difference between the eyes); the atoms.

Parameters:
  • eye (str, optional) – eye to plot (default: the first eye)

  • plot_range (tuple, optional) – (start, end) of the part of the recording to plot (plain numbers are in units)

  • units (str) – unit of the time axis (default “sec”)

  • axes (sequence of 3 Axes, optional) – axes to draw on; default: a new figure

  • figsize (tuple) – size of the new figure

Return type:

Figure

plot_experimental_setup(theta=None, phi=None, calibration=None, show_gaze_samples=True, n_gaze_samples=9, viewing_angle=None, projection='2d', title=None, axes=None, figsize=None)#

Plot visualization of eye-tracking experimental setup geometry.

Shows the spatial relationship between eye, camera, and screen using the experimental parameters stored in the EyeData object. Delegates to ExperimentalSetup.plot().

Parameters:
  • theta (Optional[float]) – Camera polar angle; a float is interpreted as radians, a string can carry units (e.g., “20 deg”). If None, uses calibration’s theta (if calibration is given), else setup’s theta.

  • phi (Optional[float]) – Camera azimuthal angle; a float is interpreted as radians, a string can carry units (e.g., “-90 deg”). If None, uses calibration’s phi (if calibration is given), else setup’s phi.

  • calibration (ForeshorteningCalibration, optional) – Fitted calibration object containing theta and phi.

  • show_gaze_samples (bool) – Show sample gaze vectors to screen positions

  • n_gaze_samples (int) – Number of sample gaze positions

  • viewing_angle (tuple) – Viewing angle for 3D projection (elev, azim) or (elev, azim, roll). Plain numbers are in degrees (as in matplotlib’s view_init); strings with units (e.g., ("30 deg", "-60 deg")) are parsed.

  • projection (str) – ‘2d’ for three orthogonal views, ‘3d’ for interactive 3D view

  • title (str) – title of the figure; default: the camera angles

  • axes (matplotlib Axes or list of Axes, optional) – axes to plot on: three axes (front, top, side view) for ‘2d’, one 3D axes for ‘3d’; default: a new figure

  • figsize (tuple) – size of the new figure

Return type:

Figure

Returns:

the figure (fig.axes are the axes of the views)

Raises:

ValueError – if the data object has no experimental_setup

Examples

Camera geometry from the experimental setup:

>>> import pypillometry as pp
>>> from pypillometry import u
>>> import matplotlib.pyplot as plt
>>> d = pp.get_example_data("rlmw_002_short")
>>> d = d.set_experimental_setup(camera_spherical=("20 deg", "-90 deg", "70 cm"))
>>> fig = d.plot.plot_experimental_setup()
../../_images/pypillometry-sim-SimPlotNamespace-3.png

To show fitted angles, pass the result of d.pupil.fit_foreshortening() as calibration=, or set theta/phi directly.

plot_heatmap(plot_range=(-inf, inf), eyes=[], show_screen=True, show_masked=False, rois=None, roi_style={}, units='sec', cmap='jet', gridsize=30, min_samples=1, smooth=None, limits=None, title=None, axes=None, figsize=None)#

Plot EyeData as a heatmap. Typically used for a large amount of data to spot the most frequent locations. To plot a scanpath, use plot_scanpath() instead. Each eye is plotted in a separate subplot; the colorbar shows the number of samples per bin. The y-axis points down (screen pixel coordinates, as in plot_calibration()).

Parameters:
  • plot_range (tuple) – The time range to plot (plain numbers are in units, or with units, e.g. (3, 5) * u.min). Default is (-np.inf, +np.inf), i.e. all data.

  • eyes (list) – The eyes to plot. Default is [], which means all available data (“left”, “right”, average, regression, …)

  • show_screen (bool) – Whether to plot the screen limits (if an experimental setup is available). Default is True.

  • show_masked (bool) – Whether to plot the masked data (because of blinks, artifacts, …; default mask policy). Default is False.

  • rois (List[ROI]) – List of ROIs (ROI) to plot. Default is None.

  • roi_style (dict) –

    Style for the ROIs, passed as keyword arguments to the ROIs’ plot() method. Default is {} (ROI defaults). Example:

    {
        "facecolor": "red",
        "edgecolor": "black",
        "linewidth": 2,
        "alpha": 0.5
    }
    

  • units (str) – The units of plain numbers in plot_range and of messages (“ms”, “sec”, “min”, “h”). Default is “sec”.

  • cmap (str) – The colormap to use. Default is “jet”.

  • gridsize (int | str) – The gridsize for the hexbin plot or histogram. If “auto”, the square root of the number of samples in plot_range is used. Default is 30.

  • min_samples (Optional[int]) – Minimum number of samples required in a bin to display it. Bins with fewer samples will not be shown. If None, automatically calculates a threshold at the 10th percentile of bin counts. Default is 1.

  • smooth (Optional[float]) – If provided, applies Gaussian smoothing to the binned histogram. The value is the sigma of the Gaussian kernel in bin units (e.g., smooth=1 applies minimal smoothing with a 1-bin sigma, smooth=2 applies more smoothing). When smooth is provided, uses a rectangular grid instead of hexbin.

  • limits (Optional[Tuple[float, float, float, float]]) – Axis limits as (xmin, xmax, ymin, ymax). If not provided, uses screen limits when available (and data falls within), otherwise uses data extent.

  • title (str) – title of the figure

  • axes (list of matplotlib.axes.Axes, optional) – axes to plot on, one per eye; default: a new figure (one subplot per eye, side by side)

  • figsize (tuple) – size of the new figure

Return type:

Figure

Returns:

the figure of the plot (fig.axes also contains the colorbars)

Raises:

ValueError – if plot_range does not overlap with the data

Examples

>>> import pypillometry as pp
>>> from pypillometry import u
>>> import matplotlib.pyplot as plt
>>> d = pp.get_example_data("rlmw_002_short")
>>> fig = d.plot.plot_heatmap(eyes="left")
../../_images/pypillometry-sim-SimPlotNamespace-4.png
plot_intervals(intervals, eyes=[], variables=[], pdf_file=None, nrow=5, ncol=3, figsize=(10, 10), show_mask=False, show_index=True)#

Plotting data around intervals.

Intervals can be extracted with get_epochs() or get_intervals(). Each interval gets a separate subplot. The data is plotted for each eye and variable in different colors. The x-axis is plotted in the units of the Intervals object. If the intervals contain event onsets, these are marked by a dashed red line.

Parameters:
  • intervals (Intervals) – the intervals to plot (e.g., from get_epochs()); Epochs are plotted in ms, with a line at each event onset

  • eyes (str | list) – eyes to plot; if empty, all available eyes are plotted

  • variables (str | list) – variables to plot; if empty, all available variables are plotted

  • pdf_file (Optional[str]) – if the name of a file is given, the figures are saved into a multi-page PDF file (missing directories are created)

  • nrow (int) – number of rows for the subplots for the intervals

  • ncol (int) – number of columns for the subplots for the intervals

  • figsize (Tuple[int, int]) – size (width, height) of each figure in inches

  • show_mask (bool) – shade samples masked (default mask policy) in any of the plotted eyes/variables

  • show_index (bool) – plot a number with the interval’s index (e.g., for identifying abnormal blinks)

Return type:

list[Figure]

Returns:

one figure per nrow x ncol intervals (also returned when pdf_file is given; the figures are then closed)

Raises:

TypeError – if intervals is not an Intervals or Epochs object

Examples

The pupil around each stimulus, one panel per interval:

>>> import pypillometry as pp
>>> from pypillometry import u
>>> import matplotlib.pyplot as plt
>>> d = pp.get_example_data("rlmw_002_short")
>>> epochs = d.get_epochs("S_", (-500, 2500) * u.ms)
>>> figs = d.plot.plot_intervals(epochs, variables="pupil", nrow=2, ncol=5,
...                              figsize=(12, 4))
../../_images/pypillometry-sim-SimPlotNamespace-5.png
plot_local_level(plot_range=(-inf, inf), eyes=[], variable='pupil', scales=None, min_coverage=0.5, max_dev=0.2, units='min', policy='strict', axes=None, figsize=None, title=None)#

Plot the local level of the pupil (see local_level()) and the scales it comes from.

For each eye, two panels: the signal (usable samples dark, others light), the medians of all scales (thin, from light for the finest to dark for the coarsest) and the local level (thick); below it, the window length chosen for each sample (dashed: the median of the whole recording) and the share of usable samples in the finest window.

Parameters:
  • plot_range (tuple) – the part to plot (plain numbers in units); default: all

  • eyes (str | list) – eyes to plot; if empty, all eyes with the variable

  • variable (str) – variable to use (default "pupil")

  • scales – settings of the local level (see local_level(); scales None: its default); to try others before using them with level= in the blink and transient functions

  • min_coverage (float) – settings of the local level (see local_level(); scales None: its default); to try others before using them with level= in the blink and transient functions

  • max_dev (float) – settings of the local level (see local_level(); scales None: its default); to try others before using them with level= in the blink and transient functions

  • units (str) – units of the time axis (default "min")

  • policy (str or MaskPolicy) – samples masked under this policy are not used (default "strict")

  • axes (sequence of Axes, optional) – two per eye; default: a new figure

  • figsize (tuple, optional) – size of a new figure

  • title (str | None) – title of the figure

Return type:

Figure

Examples

>>> import pypillometry as pp
>>> d = pp.get_example_data("rlmw_002_short")
>>> fig = d.plot.plot_local_level(eyes="left", units="sec")
../../_images/pypillometry-sim-SimPlotNamespace-6.png
plot_pupil(plot_range=(-inf, inf), eyes=[], show_events=True, show_blinks=True, show_layers=False, layers_kw=None, show_bands=True, units='sec', label_prefix='', style=None, highlight=None, highlight_color='lightblue', title=None, ax=None, layers_ax=None, **kwargs)#

Make a plot of the pupil data using matplotlib.

Has pupil-specific options which makes it different from plot_timeseries(). All eyes are plotted into one axes (ax, or the current axes).

Parameters:
  • plot_range (Tuple[float, float]) – plot from start to end (plain numbers are in units, or with units, e.g. (3, 5) * u.min)

  • eyes (str | list) – eye(s) to plot; if empty, all eyes with pupil data are plotted

  • show_events (bool) – plot events as vertical lines with labels

  • show_blinks (bool) – highlight masked or interpolated regions of the pupil data (e.g., detected blinks; the "strict" mask policy) with a red background

  • show_layers (bool) – add a panel below the pupil that shows the mask layers of the pupil of the plotted eyes and the samples that are unusable under the default mask policy (see plot_masked()); it is placed below ax (or on layers_ax). Default False.

  • layers_kw (dict) – options of the layer panel: layers, policies, show_nan and colors (see plot_masked())

  • show_bands (bool) – draw the uncertainty band of the pupil if the variables pupil_lower and pupil_upper exist (e.g., from TimescaleModel.store("signal", store_as="pupil", interval=...)): a light area in the color of the line, which does not change the limits of the axes. Default True.

  • units (str) – units of the time axis: one of “sec”=seconds (default), “ms”=millisec, “min”=minutes, “h”=hours

  • label_prefix (str) – Prefix to add to labels in the legend. Useful for overlaying multiple datasets. Default is “” (no prefix).

  • style (dict) –

    Styling for plotted lines. Can be:

    • Single dict: Applied to all eyes with automatic differentiation (e.g., {‘color’: ‘red’})

    • Dict of dicts: Per-eye styling (e.g., {‘left’: {‘linestyle’: ‘-‘}, ‘right’: {‘linestyle’: ‘–‘}})

    Default is None (uses matplotlib defaults with automatic per-eye colors and linestyles).

  • highlight (Intervals, Epochs or list of them, optional) – periods to shade in the background (e.g., trials from get_intervals()), converted to the units of the time axis

  • highlight_color (color or list of colors, optional) – color of the shading: one for all or one per element of highlight; default “lightblue”

  • title (str) – title of the plot

  • ax (matplotlib.axes.Axes, optional) – axes to plot on; default: the current axes

  • layers_ax (matplotlib.axes.Axes, optional) – axes for the layer panel (show_layers); default: new axes below ax

  • **kwargs – passed to matplotlib.axes.Axes.plot() for all eyes (after style)

Return type:

Axes

Returns:

the axes of the plot (of the pupil, without the layer panel)

Raises:

ValueError – if plot_range does not overlap with the data

Examples

Detected blinks are shaded in red, events are shown as vertical lines:

>>> import pypillometry as pp
>>> from pypillometry import u
>>> import matplotlib.pyplot as plt
>>> d = pp.get_example_data("rlmw_002_short")
>>> d = d.pupil.blinks_detect()
>>> fig, ax = plt.subplots(figsize=(10, 3))
>>> ax = d.plot.plot_pupil(plot_range=(0, 20) * u.sec, ax=ax)
../../_images/pypillometry-sim-SimPlotNamespace-7.png

Shade the trials (feedback to response) and the first second after each stimulus in different colors:

>>> import pypillometry as pp
>>> from pypillometry import u
>>> import matplotlib.pyplot as plt
>>> d = pp.get_example_data("rlmw_002_short")
>>> trials = d.get_intervals(start="F_", end="R_")
>>> stim = d.get_epochs("S_", (0, 1000) * u.ms)
>>> fig, ax = plt.subplots(figsize=(10, 3))
>>> ax = d.plot.plot_pupil(plot_range=(0, 20) * u.sec, show_blinks=False,
...                        highlight=[trials, stim],
...                        highlight_color=["lightgrey", "green"], ax=ax)
../../_images/pypillometry-sim-SimPlotNamespace-8.png

With the mask layers of both eyes in a panel below:

>>> import pypillometry as pp
>>> from pypillometry import u
>>> import matplotlib.pyplot as plt
>>> d = pp.get_example_data("rlmw_002_short")
>>> d = d.pupil.blinks_detect().pupil.blinks_interpolate()
>>> fig, ax = plt.subplots(figsize=(10, 4))
>>> ax = d.plot.plot_pupil(plot_range=(0, 20) * u.sec, show_layers=True, ax=ax)
../../_images/pypillometry-sim-SimPlotNamespace-9.png
plot_pupil_covariate(channel, plot_range=(-inf, inf), eyes=[], log=False, title=None, units='sec', ax=None, **kwargs)#

Plot the pupil size against a channel in d.aux (e.g., the luminance of the scene video or the viewing distance).

One dot per sample with a usable pupil size and a value in the channel, in one color per eye. The legend gives the correlation (Pearson’s r) of the pupil size of each eye with the channel. The samples are taken as they are: the pupil follows changes of the light with a delay, which the plot does not account for.

Parameters:
  • channel (str) – name of the channel in d.aux (e.g., "gaze_luminance")

  • plot_range (tuple) – The time range to plot (plain numbers are in units, or with units, e.g. (3, 5) * u.min). Default is (-np.inf, +np.inf), i.e. all data.

  • eyes (list) – The eyes to plot. Default is [], which means all eyes with pupil data.

  • log (bool) – if True, the axis of the channel is logarithmic and the correlation is that with the logarithm of the channel (only positive values are used); e.g. for the viewing distance. Default False.

  • title (str) – The title of the plot.

  • units (str) – The units of plain numbers in plot_range (“ms”, “sec”, “min”, “h”). Default “sec”.

  • ax (matplotlib.axes.Axes, optional) – axes to plot on; default: the current axes

  • **kwargs – passed to matplotlib.axes.Axes.scatter() (e.g., s, alpha)

Return type:

Axes

Returns:

the axes of the plot

Raises:

ValueError – if the object has no pupil data or no channel channel in d.aux, or plot_range does not overlap with the data

Examples

>>> import pypillometry as pp
>>> d = pp.HeadMountedEyeData.from_tobii_prolab("rec.xlsx")
>>> d = d.scene.luminance().scene.distance()
>>> ax = d.plot.plot_pupil_covariate("gaze_luminance")
>>> ax = d.plot.plot_pupil_covariate("gaze_distance", log=True)
plot_pupil_foreshortening_error_surface(plot_range=(-inf, inf), eyes=[], units='sec', show_screen=True, cmap='jet', gridsize=30, vmin=None, vmax=None, min_samples=None, smooth=None, limits=None, title=None, axes=None, figsize=None)#

Plot a heatmap showing average pupil size across x/y gaze positions.

This visualizes how pupil size varies across different gaze positions, which can reveal foreshortening effects (pupils appear smaller when looking away from the camera) or other spatial artifacts. Each eye is plotted in a separate subplot.

Parameters:
  • plot_range (tuple) – The time range to include in the analysis (plain numbers are in units, or with units, e.g. (3, 5) * u.min). Default is (-np.inf, +np.inf), i.e. all data.

  • eyes (Union[str, List[str]]) – Which eye(s) to plot: “left”, “right”, “average”, or a list of these. Default is [] which plots all eyes with pupil and gaze data; a requested eye without them raises a KeyError.

  • units (str) – Time units of the plot. Default is “sec”.

  • show_screen (bool) – Whether to plot the screen limits. Default is True.

  • cmap (str) – Colormap to use. Default is “jet”.

  • gridsize (int) – Number of bins in each direction. Default is 30.

  • vmin (Optional[float]) – Minimum value for color scale. If None, uses data minimum.

  • vmax (Optional[float]) – Maximum value for color scale. If None, uses data maximum.

  • min_samples (Optional[int]) – Minimum number of samples required in a bin to display it. Bins with fewer samples will not be shown. If None (default), automatically calculates a threshold at the 10th percentile of bin counts, effectively displaying only the top 90% of bins by sample count.

  • smooth (Optional[float]) – If provided, applies Gaussian smoothing to the binned surface. The value is the sigma of the Gaussian kernel in bin units (e.g., smooth=1 applies minimal smoothing with a 1-bin sigma, smooth=2 applies more smoothing). When smooth is provided, uses a rectangular grid instead of hexbin.

  • limits (Optional[Tuple[float, float, float, float]]) – Axis limits as (xmin, xmax, ymin, ymax). If not provided, uses screen limits when available (and data falls within), otherwise uses data extent.

  • title (str) – title of the figure

  • axes (list of matplotlib.axes.Axes, optional) – axes to plot on, one per eye; default: a new figure (one subplot per eye, side by side)

  • figsize (tuple) – size of the new figure

Return type:

Figure

Returns:

the figure of the plot (fig.axes also contains the colorbars)

Examples

Average pupil size at each gaze position of the left eye:

>>> import pypillometry as pp
>>> from pypillometry import u
>>> import matplotlib.pyplot as plt
>>> d = pp.get_example_data("rlmw_002_short")
>>> fig = d.plot.plot_pupil_foreshortening_error_surface(eyes="left")
../../_images/pypillometry-sim-SimPlotNamespace-10.png

vmin/vmax set the color range, min_samples hides bins with few samples and smooth applies Gaussian smoothing.

plot_pupil_segments(pdf_file=None, interv='1 min', figsize=(15, 5), ylim=None, units='sec', **kwargs)#

Plot the whole dataset chunked up into segments (usually to a PDF file).

Parameters:
  • pdf_file (Optional[str]) – file name to store the PDF; if None, no PDF is written

  • interv (float) – duration of each of the segments to be plotted (plain numbers are in units, or with units, e.g. "2 min"); default 1 min

  • figsize (Tuple[int,int]) – dimensions of the figures

  • ylim (Tuple[float,float] or None) – y-axis limits for the plots; if None, matplotlib’s automatic limits are used

  • units (str) – Units of the time axis, passed to plot_pupil(). Default “sec”.

  • **kwargs – arguments passed to plot_pupil() (e.g., highlight and highlight_color)

Return type:

list[Figure]

Returns:

one figure per segment (also returned when pdf_file is given; the figures are then closed)

Examples

Split the 40-second recording into 10-second pieces (one figure each, here only the first is shown):

>>> import pypillometry as pp
>>> from pypillometry import u
>>> import matplotlib.pyplot as plt
>>> d = pp.get_example_data("rlmw_002_short")
>>> d = d.pupil.blinks_detect()
>>> figs = d.plot.plot_pupil_segments(interv=10 * u.sec, units="sec",
...                                   figsize=(10, 3))
>>> for f in figs[1:]:
...     plt.close(f)
../../_images/pypillometry-sim-SimPlotNamespace-11.png

With pdf_file="segments.pdf", the figures are written to a PDF file instead.

plot_pupil_spectrum(eyes=[], variable='pupil', window='200 s', scale='log%', per_decade=20, policy='default', ax=None, title=None, **kwargs)#

Plot the power spectrum of the pupil size on logarithmic axes.

The spectra come from d.pupil.spectrum() (Welch’s method; windows with many unusable samples are skipped) and are averaged in log-spaced frequency bands. A power law (e.g., 1/f) is a straight line; responses that are locked to a fixed rhythm of the trials show up as narrow peaks.

Parameters:
  • eyes (str | list) – eyes to plot; if empty, all eyes with the variable

  • variable (str) – variable to use (default "pupil")

  • window (float, str or Quantity) – length of the windows (plain numbers are ms; default 200 s)

  • scale (str) – "log%" (default): spectrum of the change relative to the median in percent, \(100 \log(x / \mathrm{median})\); "original": of the signal in its units

  • per_decade (int) – number of frequency bands per factor of 10 (default 20); None: all frequencies

  • policy (str, MaskPolicy or list of str) – mask policy that decides which samples are usable; default "default"

  • ax (matplotlib Axes, optional) – axes to draw on; default: the current axes

  • title (str | None) – title of the plot

  • **kwargs – passed to ax.plot

Return type:

Axes

Examples

>>> import pypillometry as pp
>>> d = pp.get_example_data("rlmw_002").pupil.blinks_detect()
>>> ax = d.plot.plot_pupil_spectrum(window="100 s")
../../_images/pypillometry-sim-SimPlotNamespace-12.png
plot_scanpath(plot_range=(-inf, inf), eyes=[], show_screen=True, rois=None, roi_style={}, show_onsets=True, title=None, units='sec', ax=None)#

Plot EyeData as a scanpath. Typically used for single trials or another small amount of data. To plot a larger amount of data, use plot_heatmap() instead.

If several eyes are available, they are plotted in the same figure in different colors. You can choose between them using the eyes parameter. The samples are drawn as dots colored by time. The y-axis points down (screen pixel coordinates, as in plot_calibration()).

Parameters:
  • plot_range (tuple) – The time range to plot (plain numbers are in units, or with units, e.g. (3, 5) * u.min). Default is (-np.inf, +np.inf), i.e. all data.

  • eyes (list) – The eyes to plot. Default is [], which means all available data (“left”, “right”, average, regression, …)

  • show_screen (bool) – Whether to plot the screen limits (if an experimental setup is available). Default is True.

  • rois (List[ROI]) – List of ROIs (ROI) to plot. Default is None.

  • roi_style (dict) –

    Style for the ROIs, passed as keyword arguments to the ROIs’ plot() method. Default is {} (ROI defaults). Example:

    {
        "facecolor": "red",
        "edgecolor": "black",
        "linewidth": 2,
        "alpha": 0.5
    }
    

  • show_onsets (bool) – Whether to plot the event labels at the gaze position at event onset. Plotted only for the first eye. Default is True.

  • title (str) – The title of the plot.

  • units (str) – The units of the time axis and of plain numbers in plot_range (“ms”, “sec”, “min”, “h”). Default “sec”.

  • ax (matplotlib.axes.Axes, optional) – axes to plot on; default: the current axes

Return type:

Axes

Returns:

the axes of the plot

Raises:

ValueError – if plot_range does not overlap with the data

Examples

Two seconds of gaze of the left eye:

>>> import pypillometry as pp
>>> from pypillometry import u
>>> import matplotlib.pyplot as plt
>>> d = pp.get_example_data("rlmw_002_short")
>>> fig, ax = plt.subplots(figsize=(6, 5))
>>> ax = d.plot.plot_scanpath(plot_range=(10, 12) * u.sec, eyes="left", ax=ax)
../../_images/pypillometry-sim-SimPlotNamespace-13.png
plot_task_events(plot_range=None, units='sec', ax=None)[source]#

The events of the task of a simulation (see Task): one lane per event label, stimuli as bars over their duration, responses as ticks, coloured by condition.

Parameters:
  • plot_range (tuple, optional) – (start, end) of the part of the recording to plot (plain numbers are in units); default: the first 30 s

  • units (str) – unit of the time axis (default “sec”)

  • ax (Axes, optional) – axes to draw on (default: the current axes)

Return type:

Axes

plot_timeseries(plot_range=(-inf, inf), variables=[], eyes=[], units='sec', show_onsets='line', show_masked=True, show_mask_highlight=True, show_layers=False, layers_kw=None, show_bands=True, label_prefix='', style=None, highlight=None, highlight_color='lightblue', title=None, axes=None, figsize=None, **kwargs)#

Plot a part of the data. Each variable is plotted in a separate subplot (one below the other), all eyes in the same subplot.

variables can name the variables of the eyes (e.g., "pupil") and channels in d.aux:

  • the name of a channel (e.g., "gaze_luminance")

  • the first or the last part of the names of several channels, which are plotted in one subplot (e.g., "gyro" for gyro_x, gyro_y and gyro_z; "luminance" for scene_luminance and gaze_luminance)

Parameters:
  • plot_range (tuple) – The time range to plot; plain numbers are in units, values with units are converted (e.g. (0, 20) * u.sec). Default is (-np.inf, +np.inf), i.e. all data.

  • variables (list) – The data to plot, one subplot each in this order: variables of the eyes (“x”, “y”, “pupil”) and channels in d.aux (see above). Default is [], which means all variables of the eyes (and no channels of d.aux).

  • eyes (list) – The eyes to plot. Default is [], which means all available data (“left”, “right”, “both”, …). Channels in d.aux of the other eyes (e.g., right_distance for eyes="left") are left out.

  • units (str) – The units of the time axis and of plain numbers in plot_range (“ms”, “sec”, “min”, “h”). Default “sec”.

  • show_onsets (str) – Whether to plot markers for the event onsets. One of “line” (vertical lines), “label” (text label), “both” (both lines and labels), or “none” (no markers). Default is “line”.

  • show_masked (bool) – Whether to plot the data of the eyes in masked regions (default True).

  • show_mask_highlight (bool) – Whether to highlight masked regions of the data of the eyes with a light red background. Default is True.

  • show_layers (bool) – add a panel at the bottom with the mask layers of the plotted variables of the eyes (see plot_masked()). Default False.

  • layers_kw (dict) – options of the layer panel: layers, policies, show_nan and colors (see plot_masked())

  • show_bands (bool) – draw the uncertainty band of a variable V of the eyes if V_lower and V_upper exist: a light area in the color of its line, which does not change the limits of the axes; the limits are then not plotted on their own. Default True.

  • label_prefix (str) – Prefix to add to labels in the legend. Default is “” (no prefix).

  • style (dict) – Styling for the lines of the eyes: one dict for all eyes or one dict per eye (e.g., {'left': {'linestyle': '-'}}).

  • highlight (Intervals, Epochs or list of them, optional) – periods to shade in the background, converted to the units of the time axis

  • highlight_color (color or list of colors, optional) – color of the shading: one for all or one per element of highlight; default “lightblue”

  • title (str) – title of the figure

  • axes (list of matplotlib.axes.Axes, optional) – axes to plot on, one per variable and one for the layer panel (show_layers); default: a new figure

  • figsize (tuple) – size of the new figure

  • **kwargs – passed to matplotlib.axes.Axes.plot() for all lines

Return type:

Figure

Returns:

the figure of the plot

Raises:

ValueError – if a name in variables is neither a variable of the eyes nor a channel in d.aux, if show_onsets is not one of the allowed values, if plot_range does not overlap with the data or if axes does not contain one axes per variable

Examples

>>> import pypillometry as pp
>>> d = pp.HeadMountedEyeData.from_tobii_prolab("rec.xlsx")
>>> d = d.scene.luminance().scene.head_movement()
>>> fig = d.plot.plot_timeseries((60, 90), variables=["pupil", "luminance",
...                                                   "head_speed", "gyro"])
plot_timeseries_segments(pdf_file=None, interv='1 min', figsize=(15, 5), ylim=None, eyes=[], variables=[], units='sec', **kwargs)#

Plot the whole dataset chunked up into segments (usually to a PDF file).

Parameters:
  • pdf_file (str) – file name to store the PDF; if None, no PDF is written

  • interv (float) – duration of each of the segments to be plotted (plain numbers are in units, or with units, e.g. 10 * u.sec); default 1 min

  • figsize (Tuple[int,int]) – dimensions of the figures

  • ylim (Tuple[float,float], dict or None) – y-axis limits: a tuple for the subplots of the variables of the eyes (not those of channels in d.aux, which have other units), or a dict with limits per subplot (e.g., {"pupil": (2, 6), "distance": (500, 700)}); default None: automatic limits

  • eyes (list) – list of eyes to plot; if empty, all available eyes are plotted

  • variables (list) – list of variables to plot; if empty, all available variables of the eyes are plotted. Channels in d.aux can be given as well (see plot_timeseries()).

  • units (str) – units for the time axis (and plain numbers in interv); default “sec”

  • **kwargs – additional arguments passed to plot_timeseries() (e.g., highlight and highlight_color)

Return type:

list[Figure]

Returns:

one figure per segment (also returned when pdf_file is given; the figures are then closed)

Raises:

ValueError – if ylim is a dict with keys that are not plotted

Examples

Split the 40-second recording into 10-second pieces (one figure each, here only the first is shown):

>>> import pypillometry as pp
>>> from pypillometry import u
>>> import matplotlib.pyplot as plt
>>> d = pp.get_example_data("rlmw_002_short")
>>> figs = d.plot.plot_timeseries_segments(interv=10 * u.sec, units="sec",
...                                        variables="pupil", figsize=(10, 3))
>>> for f in figs[1:]:
...     plt.close(f)
../../_images/pypillometry-sim-SimPlotNamespace-14.png

With pdf_file="segments.pdf", the figures are written to a PDF file instead.

plot_truth(eyes=[], plot_range=None, units='sec', ax=None)[source]#

The pupil data with the true pupil: as measured without noise and, if they differ (e.g., by foreshortening), the true pupil size. The true extent of the blinks (where the lid covers more than 1% of the pupil) is shaded.

Parameters:
  • eyes (str or list) – eyes to plot; if empty, all eyes with pupil data

  • plot_range (tuple, optional) – (start, end) of the part of the recording to plot (plain numbers are in units)

  • units (str) – unit of the time axis (default “sec”)

  • ax (Axes, optional) – axes to draw on (default: the current axes)

Return type:

Axes

WARN_SEGMENTS = 500#

a *_segments plot with more figures than this warns