Plotting (d.plot)#
Each data object has a plot namespace with the plotting functions, e.g.
d.plot.plot_pupil() (see Plotting). You do not create
it yourself. The plots draw into the current matplotlib figure (or create
one).
Time series#
Make a plot of the pupil data using matplotlib. |
|
Plot a part of the data. |
|
Plot the whole dataset chunked up into segments (usually to a PDF file). |
|
Plot the power spectrum of the pupil size on logarithmic axes. |
|
Plot the whole dataset chunked up into segments (usually to a PDF file). |
|
Plot the pupil size against a channel in |
Blinks, masks and intervals#
Plot detected blinks in separate subplots. |
|
Plot the detected blinks in groups of similar shape. |
|
Plot the local level of the pupil (see |
|
|
|
Plotting data around intervals. |
Gaze#
Plot EyeData as a heatmap. |
|
Plot EyeData as a scanpath. |
|
Plot spatial calibration data for one or more eyes in subplots. |
Scene video (HeadMountedEyeData)#
|
Plot the gaze position during a time interval as a scanpath on a frame of the scene video. |
Experimental setup and foreshortening#
Plot visualization of eye-tracking experimental setup geometry. |
|
Plot a heatmap showing average pupil size across x/y gaze positions. |
The segmented data have their own plots
(SegmentedEyeData.plot(),
seg.pupil.plot(),
seg.gaze.plot_roi()).
All plots#
- class pypillometry.plot.PlotNamespace(data=None)[source]#
Plotting methods of an
EyeDataobject, used asd.plot(e.g.,d.plot.plot_timeseries()).Like
d.pupilandd.gaze, it is a view on the data object with no state of its own (seeNamespace). It combines the generic plots, the pupil plots, the gaze plots and the plots of the additional channels (d.aux), which are written in separate modules. Plots that need channels the object does not have raise a ValueError.- plot_blink_clusters(eyes=[], window=(200, 500), n_clusters=3, min_size=0.02, figsize=None, title=None, axes=None, seed=None)#
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 datawindow (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 groupfigsize (
tuple) – size of the figure; default: 4 x 4.5 inches per paneltitle (
str) – title of the figureaxes (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:
- 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)
- plot_blinks(eyes=[], variables='pupil', pdf_file=None, nrow=5, ncol=3, figsize=(10, 10), pre_blink=200, post_blink=200, units='sec', show_index=True)#
Plot detected blinks in separate subplots.
- Parameters:
nrow (
int) – Number of rows per figurencol (
int) – Number of columns per figurefigsize (
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:
- 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")
- 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 figureaxes (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:
- 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_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 positionsn_gaze_samples (
int) – Number of sample gaze positionsviewing_angle (
tuple) – Viewing angle for 3D projection (elev, azim) or (elev, azim, roll). Plain numbers are in degrees (as in matplotlib’sview_init); strings with units (e.g.,("30 deg", "-60 deg")) are parsed.projection (
str) – ‘2d’ for three orthogonal views, ‘3d’ for interactive 3D viewtitle (
str) – title of the figure; default: the camera anglesaxes (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:
- Returns:
the figure (
fig.axesare 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()
To show fitted angles, pass the result of
d.pupil.fit_foreshortening()ascalibration=, or settheta/phidirectly.
- 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 inplot_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 figureaxes (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:
- Returns:
the figure of the plot (
fig.axesalso 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")
- 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()orget_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., fromget_epochs()); Epochs are plotted in ms, with a line at each event onseteyes (
str|list) – eyes to plot; if empty, all available eyes are plottedvariables (
str|list) – variables to plot; if empty, all available variables are plottedpdf_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 intervalsncol (
int) – number of columns for the subplots for the intervalsfigsize (
Tuple[int,int]) – size (width, height) of each figure in inchesshow_mask (
bool) – shade samples masked (default mask policy) in any of the plotted eyes/variablesshow_index (
bool) – plot a number with the interval’s index (e.g., for identifying abnormal blinks)
- Return type:
- 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
IntervalsorEpochsobject
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))
- 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 variablevariable (
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 withlevel=in the blink and transient functionsmin_coverage (
float) – settings of the local level (seelocal_level(); scales None: its default); to try others before using them withlevel=in the blink and transient functionsmax_dev (
float) – settings of the local level (seelocal_level(); scales None: its default); to try others before using them withlevel=in the blink and transient functionsunits (
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
- Return type:
Examples
>>> import pypillometry as pp >>> d = pp.get_example_data("rlmw_002_short") >>> fig = d.plot.plot_local_level(eyes="left", units="sec")
- 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 plottedshow_events (
bool) – plot events as vertical lines with labelsshow_blinks (
bool) – highlight masked or interpolated regions of the pupil data (e.g., detected blinks; the"strict"mask policy) with a red backgroundshow_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 (seeplot_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 (seeplot_masked())show_bands (
bool) – draw the uncertainty band of the pupil if the variablespupil_lowerandpupil_upperexist (e.g., fromTimescaleModel.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”=hourslabel_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 axishighlight_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 plotax (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:
- 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)
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)
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)
- 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 ind.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:
- 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 figureaxes (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:
- Returns:
the figure of the plot (
fig.axesalso 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")
vmin/vmaxset the color range,min_sampleshides bins with few samples andsmoothapplies 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 writteninterv (
float) – duration of each of the segments to be plotted (plain numbers are in units, or with units, e.g."2 min"); default 1 minylim (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 toplot_pupil(). Default “sec”.**kwargs – arguments passed to
plot_pupil()(e.g., highlight and highlight_color)
- Return type:
- 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)
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 variablevariable (
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 unitsper_decade (
int) – number of frequency bands per factor of 10 (default 20); None: all frequenciespolicy (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
**kwargs – passed to
ax.plot
- Return type:
Examples
>>> import pypillometry as pp >>> d = pp.get_example_data("rlmw_002").pupil.blinks_detect() >>> ax = d.plot.plot_pupil_spectrum(window="100 s")
- 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:
- 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)
- 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 ind.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"forgyro_x,gyro_yandgyro_z;"luminance"forscene_luminanceandgaze_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 ind.aux(see above). Default is [], which means all variables of the eyes (and no channels ofd.aux).eyes (
list) – The eyes to plot. Default is [], which means all available data (“left”, “right”, “both”, …). Channels ind.auxof the other eyes (e.g.,right_distanceforeyes="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 (seeplot_masked()). Default False.layers_kw (
dict) – options of the layer panel: layers, policies, show_nan and colors (seeplot_masked())show_bands (
bool) – draw the uncertainty band of a variableVof the eyes ifV_lowerandV_upperexist: 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 figureaxes (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:
- 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 writteninterv (
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 minylim (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 limitseyes (
list) – list of eyes to plot; if empty, all available eyes are plottedvariables (
list) – list of variables to plot; if empty, all available variables of the eyes are plotted. Channels ind.auxcan be given as well (seeplot_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:
- 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)
With
pdf_file="segments.pdf", the figures are written to a PDF file instead.
- WARN_SEGMENTS = 500#
a
*_segmentsplot with more figures than this warns