Plotting

This file contains functions and classes related to visualization. It is basically a wrapper around seaborn, with several modifications to make it prettier and easier to scale up.

class lazyfmri.plotting.Defaults[source]

Bases: object

Default settings for plotting.

Parameters:
  • pad_title (int) – Set the distance between the title and the plot. Default = 20

  • title_size (int) – Set the font size of titles. Default = 22; you can set it equal to font_size (or any other size) by specifying “font_size”.

  • font_size (int) – Set the font size of axis labels/titles. Default = 18

  • label_size (int) – Set the font size of tick labels. Default = 14

  • tick_width (float) – Set the line-width of the ticks. Default = 0.5

  • tick_length (float) – Set the length of the ticks. Default = 0 (no ticks)

  • axis_width (float) – Set the line-width of axes. Default = 0.5

  • line_width (int) – Line widths for either all graphs (then int) or a list with the number of elements as requested graphs, default=1.

  • line_style (str) – Set the style of data in line-plots. Default = “solid”

  • sns_offset (int) – Set the distance between y-axis and start of plot. Default = None

  • sns_trim (bool) – Trim the axes following seaborn’s convention. Default = False

  • sns_bottom (bool) – Trim specifically the x-axis of plots. Default = False

  • sns_ori (str, optional) – Default orientation for bar-plots. Default is up-right (vertical). Allowed options are “v” or “h”. lazyfmri.plotting.LazyBar()

  • sns_rot (int, float, optional) – Rotation of labels in bar plot. Specific to lazyfmri.plotting.LazyBar()

  • xkcd (bool) – Plot with cartoon style. Default = False

  • ylim_bottom (float) – Set the y-limiter at the bottom of the plot. Default = None

  • ylim_top (float) – Set the y-limiter at the top of the plot. Default = None

  • xlim_left (float) – Set the x-limiter at the left of the plot. Default = None

  • xlim_right (float) – Set the x-limiter at the right of the plot. Default = None

  • set_xlim_zero (bool) – Set the distance between plot and y-axis to 0. Default = False

  • legend_handletext (float) – Set the distance between the handle and text in legends. Default = 0.05 (bit closer than default)

  • x_label (str, optional) – Label of x-axis, by default None

  • y_label (str, optional) – Label of y-axis, by default None

  • labels (str, list, optional) – String (if 1 timeseries) or list (with the length of ts) of colors, by default None. Labels for the timeseries to be used in the legend

  • title (str, dict, optional) –

    String of dictionary collecting the following keys representing information about the title:

    title = {
        'title' "some title",   # title text
        'color': 'k',           # color (default = 'k')
        'fontweight': "bold"    # fontweight (default = 'normal'), can be any of the matplotib fontweight options
    (e.g., 'italic', 'bold', 'normal' etc.)
    }
    

  • color (str, list, optional) – String (if 1 timeseries) or list (with the length of ts) of colors, by default None. If nothing is specified, we’ll use cmap to create a color palette

  • save_as (str, list, optional) – Save the plot, by default None. If you want to use figures in Inkscape, save them as PDFs to retain high resolution; specify a list of strings to save the plot with multiple extensions

  • y_lim (list, optional) – List for self._set_ylim

  • x_lim (list, optional) – List for self_.set_xlim

  • x_dec (int, optional) – Enforce x_ticks to have x_dec decimal accuracy. Default is whatever the data dictates

  • y_dec (int, optional) – Enforce y_ticks to have y_dec decimal accuracy. Default is whatever the data dictates

  • add_hline (dict, optional) –

    Dictionary for a horizontal line through the plot, by default None. Collects the following items:

    add_hline = {
        'pos' 0,        # position
        'color': 'k',   # color
        'lw': 1,        # linewidth
        'ls': '--'      # linestyle
    }
    

    You can get the settings above by specifying add_hline=’default’. Now also accepts add_hline=’mean’ for single inputs

  • add_vline (dict, optional) – Dictionary for a vertical line through the plot, by default None. Same keys as add_hline

  • dpi (int, optional) – Save figures with DPI-value. Default is 300

  • figure_background_color (str, optional) – Background of images. Default is “white”

  • bbox_inches (str, optional) – Bounding box settings. Default is “tight”

add_label_to_line(ax, pos=None, lbl=None, ori='vline', l_max=0.85, boxstyle='round', pad=0.2, fc='white', ec='white', alpha=1, **kwargs)[source]

Add a label to a vertical or horizontal reference line.

Places a text label at a fixed position along an axis-aligned line using mixed data/axes transforms. For vertical lines, x is in data units and y in axes coordinates; for horizontal lines, y is in data units and x in axes coordinates. A rounded text box is added by default.

Parameters:
  • ax (matplotlib.axes.Axes) – Target axes to draw on.

  • pos (float) – Line position in data coordinates. Interpreted as x when ori=’vline’ and as y when ori!=’vline’ (i.e., horizontal line).

  • lbl (str or float, optional) – Label text. If None, the value of pos is used. Default = None.

  • ori ({'vline', 'hline'}, optional) – Orientation of the line to label. ‘vline’ places a label on a vertical line with text rotated 90°, ‘hline’ on a horizontal line with no rotation. Default = ‘vline’.

  • l_max (float, optional) – Position along the orthogonal axis in axes coordinates [0, 1] where the label is placed (e.g., height within the axes for a vertical line). Default = 0.85.

  • boxstyle (str, optional) – Matplotlib fancy box style string (e.g., ‘round’, ‘round4’, ‘square’, ‘larrow’, ‘rarrow’). Combined internally as f"{boxstyle},pad={pad}". Default = ‘round’.

  • pad (float, optional) – Padding for the text box (in fraction of font size) passed to the boxstyle. Default = 0.2.

  • fc (str, optional) – Face color of the label’s bounding box. Default = ‘white’.

  • ec (str, optional) – Edge color of the label’s bounding box. Default = ‘white’.

  • alpha (float, optional) – Transparency of the label’s bounding box. Default = 1.

  • **kwargs – Additional keyword arguments forwarded to matplotlib.axes.Axes.text(). If bbox is provided here, it is merged with the defaults; any provided keys (e.g., fontsize, fontweight, bbox, ha, va, rotation) override the internal defaults.

Notes

  • Transform logic:
    • ori=’vline’: coordinates are (x=data, y=axes) via

    ax.get_xaxis_transform(), with default rotation 90°. - ori!=’vline’ (horizontal): coordinates are (x=axes, y=data) via ax.get_yaxis_transform(), with default rotation 0°.

  • Default text alignment is centered both horizontally and vertically.

  • The text is drawn with clip_on=False and zorder=3.

  • The function merges user-supplied bbox/style kwargs with sensible

defaults so you can override only what you need.

Returns:

The same ax object, to allow for method chaining.

Return type:

matplotlib.axes.Axes

Examples

Add a label to a vertical line at x=0 near the bottom of the axes with ‘onset’ text:

# example argument passed on :class:`lazyfmri.plotting.LazyLine()`
add_vline={
    "pos": 0,
    "add_label": {
        "lbl": "onset",
        "l_max": 0.15
    }
}
# multi-position lines
add_vline={
    "pos": [0, 1, 4],
    "add_label": [
        {
            "lbl": "t=pos", # t=0
            "l_max": 0.15,
        },
        {
            "lbl": "t=pos", # t=1
            "l_max": 0.15,
        },
        {
            "lbl": "t=pos", # t=4
            "l_max": 0.15,
        }
    ]
}
update_rc(font)[source]

update font

class lazyfmri.plotting.LazyBar[source]

Bases: object

Wrapper around seaborn.barplot() to follow the same aesthetics of the other Lazy* functions. It is strongly recommended to use a dataframe for this function to make the formatting somewhat easier, but you can input arrays for x and y. You can round the edges of the bar using fancy=True.

Parameters:
  • data (pd.DataFrame, optional) – Input dataframe, by default None

  • x (str, list, np.ndarray, optional) – Variable for the x-axis, by default None. Can be a column name from data, or a list/np.ndarray with labels for input y.

  • y (str, list, np.ndarray, optional) – Variable for the y-axis, by default None. Can be a column name from data, or a list/np.ndarray. If x is not specified, indices from 0 to y.shape will be used to construct the input dataframe.

  • labels (list, np.ndarray, optional) – custom labels that can be used when x denotes a column name in dataframe data. The replacing labels should have the same length as the labels that are being overwritten.

  • axs (<AxesSubplot:>, optional) – Subplot axis to put the plot on, by default None

  • add_points (bool, optional) – Add the actual datapoints rather than just the bars, by default False. Though default is False

  • points_color (str, tuple, optional) – Color of the points if you do not have nested categories, by default None

  • points_palette (list, sns.palettes._ColorPalette, optional) – Color palette for the points if you have nested categories (e.g., multiple variables per subject so you can color the individual subjects’ data points), by default None

  • points_cmap (str, optional) – Color map for the points if you did not specify points_palette, by default “viridis”

  • points_legend (bool, optional) – Add legend of the data points (if you have nested categories), by default False. The functionality of these interchangeable legends (bar_legend and points_legend) is quite tricky, so user discretion is advised.

  • points_alpha (float, optional) – Alpha of the points, by default 1. Sometimes useful to adjust if you have LOADS of data points

  • error (str, optional) – Type of error bar to use for the bar, by default “sem”. Can be {‘sem’|’se’} or {‘std’|’sd’. Internally, we’ll check if there’s enough samples to calculate errors from, otherwise error will be set to None

  • fancy (bool, optional) – Flag to round the edges of the bars, by default False. By default, the rounding is scaled by the min/max of the plot, regardless whether lim was specified. This ensures equal rounding across inputs. The other fancy-arguments below are a bit vague, so leaving them default will ensure nice rounding of the bars

  • fancy_rounding (float, optional) – Amount of rounding, by default 0.15

  • fancy_pad (float, optional) – Vague variable, by default -0.004

  • fancy_aspect (float, optional) – Vague variable, by default None. If None, the rounding is scaled by the min/max of the plot, regardless whether lim was specified.

  • fancy_denom (int, optional) – Scaling factor for fancy_aspect, by default 4 (which works well for data where the max value is ~50). Use higher values (e.g., 6) if your data range is large

  • bar_legend (bool, optional) – Legend for the bars, rather than points, by default False. The functionality of these interchangeable legends (bar_legend and points_legend) is quite tricky, so user discretion is advised.

  • strip_kw – Additional kwargs passed on to seaborn’s stripplot. Several factors are being set via regular arguments in the function, such as dodge, palette, color, and hue.

  • dict – Additional kwargs passed on to seaborn’s stripplot. Several factors are being set via regular arguments in the function, such as dodge, palette, color, and hue.

  • optional – Additional kwargs passed on to seaborn’s stripplot. Several factors are being set via regular arguments in the function, such as dodge, palette, color, and hue.

Example

# this figure size works well for plots with 2 bars
fig,axs = plt.subplots(figsize=(2,8))
plotting.LazyBar(
    data=df_wm,
    x="group",
    y="t1",
    sns_ori="v",
    axs=axs,
    add_labels=True,
    palette=[con_color,mdd_color],
    add_points=True,
    points_color="k",
    trim_bottom=True,
    sns_offset=4,
    y_label2="white matter T1 (ms)",
    lim=[800,1600],
    fancy=True,
    fancy_denom=6
)

Notes

see documentation of lazyfmri.plotting.Defaults() for formatting options

connect_hue_pairs(**kwargs)[source]
connect_pairs(data, x, hue_id=None, **kwargs)[source]
plot(**kw_sns)[source]
class lazyfmri.plotting.LazyButterfly[source]

Bases: object

Wrapper for creating butterfly (tornado-style) horizontal bar plots comparing two metrics with different units or scales. The left and right metrics are independently normalized so that both occupy equal visual space around a central zero line, while value labels and tick labels retain their original units.

Parameters:
  • data (pd.DataFrame) – Input dataframe containing the variables to plot.

  • left (str) – Name of the column plotted on the left-hand side of the butterfly.

  • right (str) – Name of the column plotted on the right-hand side of the butterfly.

  • y (str) – Column containing the row labels.

  • sort_by (str, optional) – Column used for sorting the rows. Defaults to right.

  • ascending (bool, optional) – Sort in ascending order. Default is False.

  • labels (list, optional) – Custom labels replacing the values in y.

  • figsize (tuple, optional) – Figure size passed to matplotlib.

  • left_label (str, optional) – Axis label describing the left-hand metric.

  • right_label (str, optional) – Axis label describing the right-hand metric.

  • left_color (str, optional) – Color of the left-hand bars.

  • right_color (str, optional) – Color of the right-hand bars.

  • thr_color (str, optional) – Color used for threshold (irrelevance) shading.

  • thr_alpha (float, optional) – Alpha transparency of the threshold shading.

  • left_fmt (str, optional) – Format string used for left-hand value labels.

  • right_fmt (str, optional) – Format string used for right-hand value labels.

  • title (str, optional) – Figure title.

  • axs (matplotlib.axes.Axes, optional) – Existing axes to plot on. If None, a new figure is created.

  • add_grid (bool, optional) – Draw vertical grid lines.

  • left_thr (float, optional) – Threshold (in original units) for the left metric to indicate negligible or irrelevant values. The corresponding normalized region is shaded.

  • right_thr (float, optional) – Threshold (in original units) for the right metric to indicate negligible or irrelevant values. The corresponding normalized region is shaded.

  • lim (float, optional) – Symmetric axis limit after normalization. Default is 1.12.

  • bar_height (float, optional) – Height of each horizontal bar.

  • label_offset (float, optional) – Offset between bar end and value label in normalized units.

  • add_value_labels (bool, optional) – Draw numeric values next to each bar.

  • add_legend (bool, optional) – Display the legend.

  • save_as (str, optional) – Path to save the figure.

  • add_grid – Add grid lines (default = True)

  • grid_style (str, optional) – Maps to linestyle argument for grid (default = ‘–‘)

  • grid_alpha (float, optional) – Maps to alpha argument for grid (default = 0.18)

  • **kwargs – Additional keyword arguments passed to the LazyPlot defaults.

Example

pl = LazyButterfly(
    data=effects_df,
    left="delta_d",
    right="delta_LBF",
    y="parameter",
    labels=pretty_names,
    sort_by="delta_LBF",
    left_label="Loss in Cohen's d",
    right_label="Loss in LogBF",
    title="Parameter sensitivity",
    fontname="Arial",
    lim=1.2,
    right_thr=3,
    left_thr=0.05
)

Notes

The left and right metrics are independently normalized to occupy equal visual space around zero. Bar lengths therefore reflect relative changes within each metric rather than absolute magnitudes across metrics. Thresholds (left_thr and right_thr) are specified in the original units and are automatically mapped onto the normalized axis.

add_butterfly_relevance_spans()[source]

Add shaded ‘irrelevant / barely relevant’ regions around zero for a scaled butterfly plot.

Assumes both sides are scaled to [-1, 1], while thresholds are given in the original units.

plot()[source]
class lazyfmri.plotting.LazyColorbar(cmap='magma_r', txt=None, vmin=0, vmax=10, ori='vertical', ticks=None, labels=None, flip_ticks=False, flip_label=False, figsize=(3.54, 0.5), cm_nr=5, cm_decimal=3, cb_kws={}, font_kws={}, **kwargs)[source]

Bases: Defaults

static colormap_ticks(vmin=None, vmax=None, key=None, dec=3, nr=5)[source]
show()[source]
class lazyfmri.plotting.LazyCorr[source]

Bases: Defaults

Wrapper around seaborn’s regplot. Plot data and a linear regression model fit. In addition to creating the plot, you can also run a regression or correlation using pingouin by setting the corresponding argument to True.

Parameters:
  • data (pd.DataFrame, optional) – Input DataFrame. In this case, use strings representing column names for x, y, and color_by. Internally, the dataframe is parsed into arrays so that it’s compatible with matplotlib’s scatter-/ color-by functions

  • x (str, np.ndarray, list) – First variable to include in plot/regression. Can be a list/array representing data, or a column name from data

  • y (str, np.ndarray, list) – Second variable to include in plot/regression. Can be a list/array representing data, or a column name from data

  • color_by (str, np.ndarray, list) – Color the points according to a separate array. Can be a list/array representing data, or a column name from data. Default color map for this is ‘viridis’, and can be changed by passing arguments to scatter_kwargs

  • color (str, list, optional) – String representing a color, by default “#ccccccc” to color the regression fit

  • figsize (tuple, optional) – Figure dimensions as per usual matplotlib conventions, by default (8,8)

  • axs (<AxesSubplot:>, optional) – Matplotlib axis to store the figure on

  • correlation (bool, optional) – Run a correlation between x and y. The result is stored in self.correlation_result

  • regression (bool, optional) – Run a regression between x and y. The result is stored in self.regression_result

  • scatter_kwargs (dict, optional) –

    Additional options passed on to the scatter function from matplotlib. Set colorbar to nothing by passing:

    scatter_kwargs={"cbar": False}
    

  • result_to_plot (bool, optional) – Add the correlation/regression result to the plot

  • stat_kwargs (dict, optional) – Options passed on to pingouin’s stats functions

  • reg_kwargs (dict, optional) – Options passed on the seaborn’s regplot

Example

from lazyfmri import plotting
import matplotlib.pyplot as plt

# vanilla version; here, the regression fit has the same color as the dots.
fig,axs = plt.subplots(figsize=(7,7))
plotting.LazyCorr(
    x_data,
    y_data,
    axs=axs,
    x_label="add xlabel",
    y_label="add ylabel"
)
# more exotic version: color each dot differently
from lazyfmri import utils

# create color map between red and blue; return as list
fig,axs = plt.subplots(figsize=(7,7))
colors = utils.make_between_cm(["r","b], as_list=True, N=len(y_data))
for ix,val in enumerate(y_data):
    axs.plot(x_data[ix], val, 'o', color=colors[ix], alpha=0.6)

# add the regression fit
plotting.LazyCorr(
    x_data,
    y_data,
    axs=axs,
    add_points=False, # turn off points; we've already plotted them
    x_label="add xlabel",
    y_label="add ylabel"
)

Notes

see documentation of lazyfmri.plotting.Defaults() for formatting options

add_result_to_plot()[source]
plot()[source]
print_results(return_result=False)[source]
class lazyfmri.plotting.LazyHist[source]

Bases: Defaults

Wrapper around seaborn’s histogram plotter

Parameters:
  • data (numpy.ndarray) – Input data for histogram

  • kde (bool, optional) – Add kernel density plot to histogram with seaborn (https://seaborn.pydata.org/generated/seaborn.kdeplot.html). Default is False

  • hist (bool, optional) – Add histogram to plot. Default is True

  • fill (bool, optional) – Fill the area below the kde plot. Default is False

  • bins (str, optional) – Set bins for histogram; default = “auto”

  • kde_kwargs (dict, optional) – Additional arguments passed on the seaborn’s kde_plot

  • hist_kwargs (dict, optional) – Additional arguments passed on to matplotlib’s hist fuction

Return type:

matplotlib.pyplot plot

Example

from lazyfmri import plotting
import matplotlib.pyplot as plt
fig,axs = plt.subplots(figsize=(7,7))
plotting.LazyHist(
    y_data,
    axs=axs,
    kde=True,
    hist=True,
    fill=False,
    y_label2="add y_label",
    x_label2="add x_label",
    hist_kwargs={"alpha": 0.4},
    kde_kwargs={"linewidth": 4}
)

Notes

see documentation of lazyfmri.plotting.Defaults() for formatting options

plot()[source]
return_kde()[source]
class lazyfmri.plotting.LazyLine[source]

Bases: Defaults

Class for plotting because I’m lazy and I don’t want to go through the matplotlib motion everything I quickly want to visualize something. This class makes that a lot easier. It allows single inputs, lists with multiple timecourses, labels, error shadings, and much more.

Parameters:
  • ts (list, numpy.ndarray) – Input data. Can either be a single list, or a list of multiple numpy arrays. If you want labels, custom colors, or error bars, these inputs must come in lists of similar length as ts!

  • xx (list, numpy.ndarray, optional) – X-axis array

  • error (list, numpy.ndarray, optional) – Error data with the same length/shape as the input timeseries, by default None. Can be either a numpy.ndarray for 1 timeseries, or a list of numpy.ndarrays for multiple timeseries

  • error_alpha (float, optional) – Opacity level for error shadings, by default 0.3

  • cmap (str, optional) – Color palette to use for colors if no individual colors are specified, by default ‘viridis’

  • figsize (tuple, optional) – Figure dimensions as per usual matplotlib conventions, by default (25,5)

  • markers (str, list, optional) – Use markers during plotting. A single option will be applied to all elements in ts. A separate list for each element of ts is also accepted. If one array in ts should not have markers, use None. E.g., if len(ts) == 3, and we want only the first timecourse to have markers use: markers=['.',None,None]

  • markersize (str, list, optional) – Specify marker sizes during plotting. A single option will be applied to all elements in ts. A separate list for each element of ts is also accepted. If one array in ts should not have markers, use None. E.g., if len(ts) == 3, and we want only the first timecourse to have markers use: markers=['.',None,None]

  • markerfc (str, list, optional) – Specify marker facecolor during plotting. A single option will be applied to all elements in ts. A separate list for each element of ts is also accepted

  • markerec (str, list, optional) – Specify marker edgecolor during plotting. A single option will be applied to all elements in ts. A separate list for each element of ts is also accepted

  • plot_kw (dict, optional) – Further plotting options passed to matplotlib.pyplot.plot, such as markerfacecolor (removes fill from markers, leaving only the edges), and markeredgewidth (sets the width of the marker outline). These options are passed to every elements in ts.

  • x_ticks (list, optional) – Locations where to put the ticks on the x-axis

  • y_ticks (list, optional) – Locations where to put the ticks on the y-axis

Example

# create a bunch of timeseries
from lazyfmri import utils
ts = utils.random_timeseries(1.2, 0.0, 100)
ts1 = utils.random_timeseries(1.2, 0.3, 100)
ts2 = utils.random_timeseries(1.2, 0.5, 100)
ts3 = utils.random_timeseries(1.2, 0.8, 100)
ts4 = utils.random_timeseries(1.2, 1, 100)

# plot 1 timecourse
plotting.LazyLine(ts2, figsize=(20, 5))
<lazyfmri.plotting.LazyLine at 0x7f839b0289d0>
# plot multiple timecourses, add labels, and save file
plotting.LazyLine([ts, ts1, ts2, ts3, ts4], figsize=(20, 5), save_as="test_LazyLine.pdf", labels=['vol=0', 'vol=0.3',
'vol=0.5', 'vol=0.8', 'vol=1.0'])
<lazyfmri.plotting.LazyLine at 0x7f839b2177c0>
# add horizontal line at y=0
hline = {'pos': 0, 'color': 'k', 'lw': 0.5, 'ls': '--'}
plotting.LazyLine(ts2, figsize=(20, 5), add_hline=hline)
<lazyfmri.plotting.LazyLine at 0x7f839b053580>
# add shaded error bars
from scipy.stats import sem
# make some stack
stack = np.hstack((ts1[...,np.newaxis],ts2[...,np.newaxis],ts4[...,np.newaxis]))
avg = stack.mean(axis=-1) # calculate mean
err = sem(stack, axis=-1) # calculate error
plotting.LazyLine(avg, figsize=(20, 5), error=err)
<lazyfmri.plotting.LazyLine at 0x7f839b0d5220>

Notes

See https://lazyfmri.readthedocs.io/en/latest/examples/example.html for more examples

plot()[source]

main plotting function

class lazyfmri.plotting.LazyPRF[source]

Bases: Defaults

Plot the geometric location of the Gaussian pRF.

Parameters:
  • prf (numpy.ndarray) – instantiation of gauss2D_iso_cart; will be np.squeeze’ed over the first axis if ndim >= 3.

  • vf_extent (list) – the space the pRF lives in

  • cmap (str, optional) – Colormap for imshow; accepts output from lazyfmri.utils.make_binary_cm(). Defaults to ‘magma’

  • cross_color (str, optional) – Color for the fixation cross; defaults to ‘white’. You can set it to ‘k’ if you have a binary colormap as input

  • alpha (float, optional) – Opacity for imshow

  • shrink_factor (float, optional) – When the background of the image is white, we create a black border around the Circle patch. If this is equal to vf_extent, the border is cut off at some points. This factor shrinks the radius of the Circle, so that we can have a nice border. When set to 0.9, it becomes sort of like a target. This is relevant for all non-magma color maps that you insert, specifically a lazyfmri.utils.make_binary_cm() object

  • full_axis (bool, optional) – If True, the entire axis of vf_extent will be used for the ticks (more detailed). If False, a truncated/trimmed version will be returned (looks cleaner). Default = False

  • axis_off (bool, optional) – If True the x/y axis will be maintained, and the vf_extent will be given as ticks. If False, axis will be turned off. If axis_off=True, then full_axis and other label/axis parameters are ignored. Default = True

  • vf_only (bool, optional) – Only show the outline of the the visual field, without pRF. You still need to specify the pRF as we’ll imshow an empty array with the same shape rather than the pRF. Default = False

  • line_width (float, optional) – Width of the outer border of the visual field if cmap is not viridis or magma (these color maps are quite default, and do not require an extra border like lazyfmri.utils.make_binary_cm()-objects do). Default is 0.5.

  • cross_width (float, optional) – Width of the cross denoting the x/y axis. Default is 0.5, but can be increased if cmap is not viridis or magma to enhance visibility

  • z_lines (int, optional) – Set the order of the vertical/horizontal lines. Default is on top of the pRF (1)

  • z_prf (int, optional) – Set the order of the pRF imshow. Default is below the axis lines, but can be changed to be on top of them. Default = 0

  • imshow_kw (dict, optional) – Additional kwargs passed on to imshow

Return type:

matplotlib.pyplot plot

plot()[source]
class lazyfmri.plotting.LazyPoints[source]

Bases: Defaults

Wrapper for plotting jittered observations together with a summary statistic (mean ± SEM). This class provides a lightweight alternative to LazyBar when individual data points should remain visible rather than aggregated into bars.

Parameters:
  • data (pd.DataFrame) – Input dataframe containing the data to plot.

  • x (str) – Column name defining the categorical grouping variable. Each unique value will be plotted at a separate x-position.

  • y (str) – Column name containing the dependent variable.

  • figsize (tuple, optional) – Figure dimensions as per matplotlib conventions, by default (3.54, 3.54).

  • axs (matplotlib.axes.Axes, optional) – Existing matplotlib axis to plot on. If None (default), a new figure and axis are created using figsize. If supplied, figsize is ignored.

  • jitter (float, optional) – Standard deviation of the Gaussian jitter applied to the x-positions of individual observations, by default 0.05.

  • alpha (float, optional) – Transparency of the individual data points, by default 0.7.

  • point_size (float, optional) – Size of the individual scatter points, by default 30.

  • point_color (str or tuple, optional) – Fixed color for all points. If omitted, colors are taken from palette or generated from cmap.

  • palette (list or seaborn color palette, optional) – Colors assigned to each category. If omitted, a palette is generated from cmap.

  • order (list, optional) –

    Order in which the categories specified by x should be plotted. By default, categories are plotted in the order in which they appear in data. This argument behaves similarly to the order argument in seaborn categorical plotting functions.

    Example

    plotting.LazyPoints(
        data=df,
        x="condition",
        y="coef",
        order=["CSm", "CSpu", "CSpr"]
    )
    

  • cmap (str, optional) – Colormap used to generate colors when palette is not specified, by default "viridis".

  • summary_color (str or tuple, optional) – Color of the summary marker and error bar, by default "k".

  • summary_marker (str, optional) – Marker style for the summary statistic, by default "o".

  • capsize (float, optional) – Capsize of the SEM error bars, by default 4.

  • scatter_kws (dict, optional) –

    Additional keyword arguments passed to matplotlib.axes.Axes.scatter(). The following parameters are automatically set by LazyPoints unless explicitly overridden through scatter_kws:

    • s: point size (point_size)

    • alpha: point transparency (alpha)

    • color: point_color or the corresponding entry from palette

    • zorder: 2

  • error_kws (dict, optional) –

    Additional keyword arguments passed to matplotlib.axes.Axes.errorbar(). The following parameters are automatically set by LazyPoints unless explicitly overridden through error_kws:

    • fmt: summary marker (summary_marker)

    • color: summary color (summary_color)

    • lw: 2

    • capsize: capsize

    • zorder: 3

    The x-position, mean, and yerr (SEM) are computed internally and cannot be supplied through error_kws.

Notes

For each category in x, the class:

  1. Draws all observations as horizontally jittered scatter points.

  2. Computes the mean of y.

  3. Computes the standard error of the mean (SEM).

  4. Overlays the mean ± SEM as an error bar.

The resulting plot combines the interpretability of raw data visualization with a compact summary statistic, making it useful for small-to-moderate sample sizes where displaying individual observations is preferred over conventional bar plots.

Examples

plotting.LazyPoints(
    data=df,
    x="condition",
    y="coef",
    figsize=(4, 5),
    jitter=0.05,
    point_color="tab:blue",
    summary_color="k",
    y_label="Coefficient"
)

Notes

See the documentation of lazyfmri.plotting.Defaults for formatting options common to all Lazy* plotting classes.

plot()[source]
lazyfmri.plotting.RGBToPyCmap(rgbdata)[source]
lazyfmri.plotting.add_axvspan(axs, loc=(0, 2), color='#cccccc', alpha=0.3, ymin=0, ymax=1, **kwargs)[source]
lazyfmri.plotting.annotate_cortical_ribbon(axs, pial_pos=(0.02, 0.92), wm_pos=(0.02, 0.02), lbls=['pial', 'wm'], **kwargs)[source]
lazyfmri.plotting.conform_ax_to_obj()[source]

Function to conform any plot to the aesthetics of this plotting module. Can be used when a plot is created with functions other than lazyfmri.plotting.LazyLine, lazyfmri.plotting.LazyCorr, lazyfmri.plotting.LazyHist, or any other function specified in this file. Assumes ax is a matplotlib.axes._subplots.AxesSubplot object, and obj a lazyfmri.plotting.Lazy*-object.

Parameters:
  • ax (matplotlib.axes._subplots.AxesSubplot) – input axis that needs to be modified

  • obj (lazyfmri.plotting.Lazy*) – linecanning-specified plotting object containing the information with which ax will be conformed

  • kwargs (dict, optional) – other elements defined in lazyfmri.plotting.Defaults, such as font_size, label_size, or axis_width. Overwrites elements in obj, if passed

Returns:

input axis with updated aesthetics

Return type:

matplotlib.axes._subplots.AxesSubplot

Example

# convert statsmodels's QQ-plot
from lazyfmri import plotting
import matplotlib as plt
from scipy import stats

fig,ax = plt.subplots(figsize=(8,8))
sm.qqplot(mdf.resid, dist=stats.norm, line='s', ax=ax)
ax = plotting.conform_ax_to_obj(ax,pl)
lazyfmri.plotting.fig_annot(fig, axs=None, y=1.01, x0_corr=0, x_corr=-0.09, fontsize=28, lower=False, brackets=False, square=False, **kwargs)[source]
lazyfmri.plotting.make_wm_pial_ticks(data, start=0, end=100, step=25, force_int=True)[source]