Plotting

Plotting functions

class linescanning.plotting.Defaults(**kwargs)[source]

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”. linescanning.plotting.LazyBar()

  • sns_rot (int, float, optional) – Rotation of labels in bar plot. Specific to linescanning.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”

update_rc(font)[source]

update font

class linescanning.plotting.LazyBar(data: ~pandas.core.frame.DataFrame | None = None, x: str | ~numpy.ndarray | None = None, y: str | ~numpy.ndarray | None = None, labels: list | None = None, palette: list | <Mock name='mock.palettes._ColorPalette' id='140531590053600'> | None = None, cmap: str = 'inferno', hue: str | None = None, figsize=(4, 7), add_labels: bool = False, lim: list | None = None, ticks: list | None = None, add_points: bool = False, points_color: str | tuple | None = None, points_palette: list | <Mock name='mock.palettes._ColorPalette' id='140531590053600'> | None = None, points_cmap: str = 'viridis', points_legend: bool = False, points_alpha: float = 1, error: str = 'se', fancy: bool = False, fancy_rounding: float = 0.15, fancy_pad: float = -0.004, fancy_aspect: float | None = None, fancy_denom: int = 4, bar_legend: bool = False, lbl_legend: list | None = None, strip_kw: dict = {}, connect: bool = False, connect_kw: dict = {}, **kwargs)[source]

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 linescanning.plotting.Defaults() for formatting options

class linescanning.plotting.LazyColorbar(cmap='magma_r', txt=None, vmin=0, vmax=10, ori='vertical', ticks=None, labels=None, flip_ticks=False, flip_label=False, figsize=(6, 0.5), save_as=None, cm_nr=5, cm_decimal=3, cb_kws={}, font_kws={}, **kwargs)[source]
class linescanning.plotting.LazyCorr(data: DataFrame | None = None, x: str | ndarray | None = None, y: str | ndarray | None = None, color: str = '#cccccc', figsize: tuple = (7, 7), points: bool = True, label: str | None = None, scatter_kwargs: dict = {}, stat_kwargs: dict = {}, color_by: list | ndarray | None = None, regression: bool = False, correlation: bool = False, reg_kwargs: dict = {}, error_kwargs: dict = {}, result_to_plot: bool = False, result_loc: tuple = (0.55, 0.1), result_ec: tuple = (1.0, 0.5, 0.5), result_fc: tuple = (1.0, 0.8, 0.8), result_dec: int = 2, verbose=False, *args, **kwargs)[source]

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 linescanning 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 linescanning import utils
>>> #
>>> fig,axs = plt.subplots(figsize=(7,7))
>>> #
>>> # create color map between red and blue; return as list
>>> 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 linescanning.plotting.Defaults() for formatting options

class linescanning.plotting.LazyHist(data, x=None, y=None, figsize=(5, 5), kde=False, hist=True, bins='auto', fill=False, kde_kwargs={}, hist_kwargs={}, color='#cccccc', cmap=None, fancy: bool = False, fancy_rounding: float = 0.15, fancy_pad: float = -0.004, fancy_aspect: float | None = None, **kwargs)[source]

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 linescanning 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 linescanning.plotting.Defaults() for formatting options

class linescanning.plotting.LazyPRF(prf, vf_extent, cmap='RdBu_r', cross_color='white', alpha=None, shrink_factor=1, axis_off=True, figsize=(8, 8), full_axis=False, vf_only=False, cross_width=0.5, concentric=None, z_lines=1, z_prf=0, edge_color=None, imshow_kw={}, **kwargs)[source]

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 linescanning.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 linescanning.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 linescanning.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

class linescanning.plotting.LazyPlot(ts, xx=None, error=None, error_alpha=0.3, figsize=(14, 4), cmap='viridis', labels=None, markers=None, markersize=None, markerfc=None, markerec=None, plot_alpha=None, plot_kw={}, **kwargs)[source]

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 linescanning 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.LazyPlot(ts2, figsize=(20, 5))
<linescanning.plotting.LazyPlot at 0x7f839b0289d0>
>>> # plot multiple timecourses, add labels, and save file
>>> plotting.LazyPlot([ts, ts1, ts2, ts3, ts4], figsize=(20, 5), save_as="test_LazyPlot.pdf", labels=['vol=0', 'vol=0.3', 'vol=0.5', 'vol=0.8', 'vol=1.0'])
<linescanning.plotting.LazyPlot at 0x7f839b2177c0>
>>> # add horizontal line at y=0
>>> hline = {'pos': 0, 'color': 'k', 'lw': 0.5, 'ls': '--'}
>>> >>> plotting.LazyPlot(ts2, figsize=(20, 5), add_hline=hline)
<linescanning.plotting.LazyPlot 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.LazyPlot(avg, figsize=(20, 5), error=err)
<linescanning.plotting.LazyPlot at 0x7f839b0d5220>

Notes

See https://linescanning.readthedocs.io/en/latest/examples/lazyplot.html for more examples

plot()[source]

main plotting function

linescanning.plotting.conform_ax_to_obj(ax, obj=None, **lazy_args)[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 linescanning.plotting.LazyPlot, linescanning.plotting.LazyCorr, linescanning.plotting.LazyHist, or any other function specified in this file. Assumes ax is a matplotlib.axes._subplots.AxesSubplot object, and obj a linescanning.plotting.Lazy*-object.

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

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

  • **lazy_args (dict, optional) – other elements defined in linescanning.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 linescanning 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)