Skip to content

API reference — Plot functions

Auto-generated from docstrings.

behaviz.core.core

plot_bar

plot_bar(x, y, width=0.2, bottom=None, ax=None, spec=None, **overrides)

Plot a bar chart.

Parameters:

Name Type Description Default
x ndarray

bar positions, shape (N,). Array-like (list/tuple/ndarray/Series), or a column name when data= is given.

required
y ndarray

bar heights, shape (N,). Same accepted types as x.

required
width Optional[float | ndarray]

bar width — a single scalar or one width per bar, shape (N,). Defaults to 0.2.

0.2
bottom Optional[ndarray]

bar base offsets for stacked bars — scalar or shape (N,). Defaults to 0.

None
data

optional dataframe-like (pandas/polars/dict of arrays) that string channels are resolved against.

required
ax Optional[BehavizAxes]

axes to plot on (created if None).

None
spec Optional[PlotSpec]

plot specification.

None
**overrides

styling forwarded to the active backend renderer.

{}

Returns:

Type Description
(fig, ax)

backend figure and axes handles.

Raises:

Type Description
BehavizDataError

if shapes or types are inconsistent (the message names the offending argument).

Example

bv.plot_bar([0, 1, 2], [3, 5, 2], width=0.5)

Source code in behaviz/core/core.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
@plot_function(
    default_spec=DEFAULT_SPEC,
    channels=[
        Channel("x"),
        Channel("y", same_length_as="x"),
        Channel("width", kind="scalar_or_vector", required=False, same_length_as="x"),
        Channel("bottom", kind="scalar_or_vector", required=False, same_length_as="x"),
    ],
    grouping="dodge",
)
def plot_bar(
    x: np.ndarray,
    y: np.ndarray,
    width: Optional[float | np.ndarray] = 0.2,
    bottom: Optional[np.ndarray] = None,
    ax: Optional[BehavizAxes] = None,
    spec: Optional[PlotSpec] = None,
    **overrides,
) -> tuple[BehavizFigure, BehavizAxes]:
    """Plot a bar chart.

    Args:
        x: bar positions, shape (N,). Array-like (list/tuple/ndarray/Series),
            or a column name when ``data=`` is given.
        y: bar heights, shape (N,). Same accepted types as ``x``.
        width: bar width — a single scalar or one width per bar, shape (N,).
            Defaults to 0.2.
        bottom: bar base offsets for stacked bars — scalar or shape (N,).
            Defaults to 0.
        data: optional dataframe-like (pandas/polars/dict of arrays) that
            string channels are resolved against.
        ax: axes to plot on (created if None).
        spec: plot specification.
        **overrides: styling forwarded to the active backend renderer.

    Returns:
        (fig, ax): backend figure and axes handles.

    Raises:
        BehavizDataError: if shapes or types are inconsistent (the message
            names the offending argument).

    Example:
        >>> bv.plot_bar([0, 1, 2], [3, 5, 2], width=0.5)
    """
    r = get_renderer()
    r.bar(ax, x, y, width=width, bottom=bottom, **overrides)
    return ax

plot_hbar

plot_hbar(y, x, height=0.2, left=None, ax=None, spec=None, **overrides)

Plot a horizontal bar chart.

Parameters:

Name Type Description Default
y ndarray

bar positions, shape (N,). Array-like (list/tuple/ndarray/Series), or a column name when data= is given.

required
x ndarray

bar widths, shape (N,). Same accepted types as x.

required
height Optional[float | ndarray]

bar height, a single scalar or one width per bar, shape (N,). Defaults to 0.2.

0.2
left Optional[ndarray]

bar base offsets for horizontal stacked bars, scalar or shape (N,). Defaults to 0.

None
data

optional dataframe-like (pandas/polars/dict of arrays) that string channels are resolved against.

required
ax Optional[BehavizAxes]

axes to plot on (created if None).

None
spec Optional[PlotSpec]

plot specification.

None
**overrides

styling forwarded to the active backend renderer.

{}

Returns:

Type Description
(fig, ax)

backend figure and axes handles.

Raises:

Type Description
BehavizDataError

if shapes or types are inconsistent (the message names the offending argument).

Example

bv.plot_hbar([0, 1, 2], [3, 5, 2], height=0.5)

Source code in behaviz/core/core.py
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
@plot_function(
    default_spec=DEFAULT_SPEC,
    channels=[
        Channel("y"),
        Channel("x", same_length_as="y"),
        Channel("height", kind="scalar_or_vector", required=False, same_length_as="y"),
        Channel("left", kind="scalar_or_vector", required=False, same_length_as="y"),
    ],
    grouping="dodge",
)
def plot_hbar(
    y: np.ndarray,
    x: np.ndarray,
    height: Optional[float | np.ndarray] = 0.2,
    left: Optional[np.ndarray] = None,
    ax: Optional[BehavizAxes] = None,
    spec: Optional[PlotSpec] = None,
    **overrides,
) -> tuple[BehavizFigure, BehavizAxes]:
    """Plot a horizontal bar chart.

    Args:
        y: bar positions, shape (N,). Array-like (list/tuple/ndarray/Series),
            or a column name when ``data=`` is given.
        x: bar widths, shape (N,). Same accepted types as ``x``.
        height: bar height, a single scalar or one width per bar, shape (N,).
            Defaults to 0.2.
        left: bar base offsets for horizontal stacked bars, scalar or shape (N,).
            Defaults to 0.
        data: optional dataframe-like (pandas/polars/dict of arrays) that
            string channels are resolved against.
        ax: axes to plot on (created if None).
        spec: plot specification.
        **overrides: styling forwarded to the active backend renderer.

    Returns:
        (fig, ax): backend figure and axes handles.

    Raises:
        BehavizDataError: if shapes or types are inconsistent (the message
            names the offending argument).

    Example:
        >>> bv.plot_hbar([0, 1, 2], [3, 5, 2], height=0.5)
    """
    r = get_renderer()
    r.hbar(ax, y, x, height=height, left=left, **overrides)
    return ax

plot_errorbar

plot_errorbar(x, y, err, ax=None, spec=None, **overrides)

Plot data points with error bars.

Parameters:

Name Type Description Default
x ndarray

x values, shape (N,). Array-like, or a column name when data= is given.

required
y ndarray

y values, shape (N,). Same accepted types as x.

required
err ndarray

error bar sizes. shape (N,): symmetric +/- values. shape (2, N): separate lower and upper magnitudes (both positive).

required
data

optional dataframe-like the string channels are resolved against.

required
ax Optional[BehavizAxes]

axes to plot on (created if None).

None
spec Optional[PlotSpec]

plot specification.

None
**overrides

styling forwarded to the active backend renderer (e.g. capsize, elinewidth).

{}

Returns:

Type Description
(fig, ax)

backend figure and axes handles.

Raises:

Type Description
BehavizDataError

if shapes or types are inconsistent.

Example

bv.plot_errorbar(x, means, sems, capsize=4)

Source code in behaviz/core/core.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
@plot_function(
    default_spec=DEFAULT_SPEC,
    channels=[
        Channel("x"),
        Channel("y", same_length_as="x"),
        Channel("err", kind="raw"),
    ],
    grouping="dodge",
)
def plot_errorbar(
    x: np.ndarray,
    y: np.ndarray,
    err: np.ndarray,
    ax: Optional[BehavizAxes] = None,
    spec: Optional[PlotSpec] = None,
    **overrides,
) -> tuple[BehavizFigure, BehavizAxes]:
    """Plot data points with error bars.

    Args:
        x: x values, shape (N,). Array-like, or a column name when ``data=``
            is given.
        y: y values, shape (N,). Same accepted types as ``x``.
        err: error bar sizes.
            shape (N,): symmetric +/- values.
            shape (2, N): separate lower and upper magnitudes (both positive).
        data: optional dataframe-like the string channels are resolved against.
        ax: axes to plot on (created if None).
        spec: plot specification.
        **overrides: styling forwarded to the active backend renderer
            (e.g. ``capsize``, ``elinewidth``).

    Returns:
        (fig, ax): backend figure and axes handles.

    Raises:
        BehavizDataError: if shapes or types are inconsistent.

    Example:
        >>> bv.plot_errorbar(x, means, sems, capsize=4)
    """
    err = np.asarray(err)
    n = x.shape[0]
    if not (err.shape == (n,) or err.shape == (2, n)):
        raise data_error(
            "plot_errorbar",
            "`err` must be shape (N,) for symmetric or (2, N) for asymmetric errors.",
            details={"x": x, "err": err},
            hint=f"N = {n} here.",
        )

    r = get_renderer()
    r.errorbar(ax, x, y, err, **overrides)
    return ax

plot_violin

plot_violin(x, ys, ax=None, spec=None, **overrides)

Plot one violin (distribution) per x position.

Parameters:

Name Type Description Default
x ndarray

violin positions, shape (N,). Array-like, or a column name when data= is given.

required
ys list[ndarray]

the distributions — a sequence of N 1-D arrays (ragged lengths allowed), or a 2-D array read as one distribution per row.

required
data

optional dataframe-like the string channels are resolved against.

required
ax Optional[BehavizAxes]

axes to plot on (created if None).

None
spec Optional[PlotSpec]

plot specification.

None
**overrides

styling forwarded to the active backend renderer.

{}

Returns:

Type Description
(fig, ax, vp)

figure, axes, and the violin artist dict (vp["bodies"] holds one artist per violin on every backend).

Raises:

Type Description
BehavizDataError

if len(ys) != len(x) or the inputs are not numeric sequences.

Example

bv.plot_violin([0, 1, 2], [groupA, groupB, groupC])

Source code in behaviz/core/core.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
@plot_function(
    default_spec=DEFAULT_SPEC,
    channels=[
        Channel("x"),
        Channel("ys", kind="vectors", same_length_as="x"),
    ],
)
def plot_violin(
    x: np.ndarray,
    ys: list[np.ndarray],
    ax: Optional[BehavizAxes] = None,
    spec: Optional[PlotSpec] = None,
    **overrides,
) -> tuple[BehavizFigure, BehavizAxes]:
    """Plot one violin (distribution) per x position.

    Args:
        x: violin positions, shape (N,). Array-like, or a column name when
            ``data=`` is given.
        ys: the distributions — a sequence of N 1-D arrays (ragged lengths
            allowed), or a 2-D array read as one distribution per *row*.
        data: optional dataframe-like the string channels are resolved against.
        ax: axes to plot on (created if None).
        spec: plot specification.
        **overrides: styling forwarded to the active backend renderer.

    Returns:
        (fig, ax, vp): figure, axes, and the violin artist dict
            (``vp["bodies"]`` holds one artist per violin on every backend).

    Raises:
        BehavizDataError: if ``len(ys) != len(x)`` or the inputs are not
            numeric sequences.

    Example:
        >>> bv.plot_violin([0, 1, 2], [groupA, groupB, groupC])
    """
    r = get_renderer()
    vp = r.violin(ax, ys, x, **overrides)
    return ax, vp

plot_vertical

plot_vertical(x, ymin=None, ymax=None, ax=None, spec=None, **overrides)

Draw one or more vertical lines.

Parameters:

Name Type Description Default
x ndarray

x position(s) of the line(s) — a scalar or shape (N,) array-like, or a column name when data= is given.

required
ymin Optional[ndarray]

lower end(s) in axis fraction (0 = bottom, 1 = top) — scalar or shape (N,). Defaults to 0.

None
ymax Optional[ndarray]

upper end(s) in axis fraction — scalar or shape (N,). Defaults to 1.

None
data

optional dataframe-like the string channels are resolved against.

required
ax Optional[BehavizAxes]

axes to plot on (created if None).

None
spec Optional[PlotSpec]

plot specification.

None
**overrides

styling forwarded to the active backend renderer.

{}

Returns:

Type Description
(fig, ax)

backend figure and axes handles.

Raises:

Type Description
BehavizDataError

if lengths are inconsistent.

Example

bv.plot_vertical(stimulus_onset, color="#888888", linestyle="--")

Source code in behaviz/core/core.py
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
@plot_function(
    default_spec=DEFAULT_SPEC,
    channels=[
        Channel("x"),
        Channel("ymin", kind="scalar_or_vector", required=False, same_length_as="x"),
        Channel("ymax", kind="scalar_or_vector", required=False, same_length_as="x"),
    ],
)
def plot_vertical(
    x: np.ndarray,
    ymin: Optional[np.ndarray] = None,
    ymax: Optional[np.ndarray] = None,
    ax: Optional[BehavizAxes] = None,
    spec: Optional[PlotSpec] = None,
    **overrides,
) -> tuple[BehavizFigure, BehavizAxes]:
    """Draw one or more vertical lines.

    Args:
        x: x position(s) of the line(s) — a scalar or shape (N,) array-like,
            or a column name when ``data=`` is given.
        ymin: lower end(s) in axis fraction (0 = bottom, 1 = top) — scalar or
            shape (N,). Defaults to 0.
        ymax: upper end(s) in axis fraction — scalar or shape (N,).
            Defaults to 1.
        data: optional dataframe-like the string channels are resolved against.
        ax: axes to plot on (created if None).
        spec: plot specification.
        **overrides: styling forwarded to the active backend renderer.

    Returns:
        (fig, ax): backend figure and axes handles.

    Raises:
        BehavizDataError: if lengths are inconsistent.

    Example:
        >>> bv.plot_vertical(stimulus_onset, color="#888888", linestyle="--")
    """
    ymin = np.zeros(x.shape) if ymin is None else np.broadcast_to(ymin, x.shape)
    ymax = np.ones(x.shape) if ymax is None else np.broadcast_to(ymax, x.shape)

    r = get_renderer()
    for xi, ymini, ymaxi in zip(x, ymin, ymax):
        r.vertical(ax, xi, ymini, ymaxi, **overrides)

    return ax

plot_horizontal

plot_horizontal(y, xmin=None, xmax=None, ax=None, spec=None, **overrides)

Draw one or more horizontal lines.

Parameters:

Name Type Description Default
y ndarray

y position(s) of the line(s) — a scalar or shape (N,) array-like, or a column name when data= is given.

required
xmin Optional[ndarray]

left end(s) in axis fraction (0 = left, 1 = right) — scalar or shape (N,). Defaults to 0.

None
xmax Optional[ndarray]

right end(s) in axis fraction — scalar or shape (N,). Defaults to 1.

None
data

optional dataframe-like the string channels are resolved against.

required
ax Optional[BehavizAxes]

axes to plot on (created if None).

None
spec Optional[PlotSpec]

plot specification.

None
**overrides

styling forwarded to the active backend renderer.

{}

Returns:

Type Description
(fig, ax)

backend figure and axes handles.

Raises:

Type Description
BehavizDataError

if lengths are inconsistent.

Example

bv.plot_horizontal(0.5, color="#888888", linestyle=":")

Source code in behaviz/core/core.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
@plot_function(
    default_spec=DEFAULT_SPEC,
    channels=[
        Channel("y"),
        Channel("xmin", kind="scalar_or_vector", required=False, same_length_as="y"),
        Channel("xmax", kind="scalar_or_vector", required=False, same_length_as="y"),
    ],
)
def plot_horizontal(
    y: np.ndarray,
    xmin: Optional[np.ndarray] = None,
    xmax: Optional[np.ndarray] = None,
    ax: Optional[BehavizAxes] = None,
    spec: Optional[PlotSpec] = None,
    **overrides,
) -> tuple[BehavizFigure, BehavizAxes]:
    """Draw one or more horizontal lines.

    Args:
        y: y position(s) of the line(s) — a scalar or shape (N,) array-like,
            or a column name when ``data=`` is given.
        xmin: left end(s) in axis fraction (0 = left, 1 = right) — scalar or
            shape (N,). Defaults to 0.
        xmax: right end(s) in axis fraction — scalar or shape (N,).
            Defaults to 1.
        data: optional dataframe-like the string channels are resolved against.
        ax: axes to plot on (created if None).
        spec: plot specification.
        **overrides: styling forwarded to the active backend renderer.

    Returns:
        (fig, ax): backend figure and axes handles.

    Raises:
        BehavizDataError: if lengths are inconsistent.

    Example:
        >>> bv.plot_horizontal(0.5, color="#888888", linestyle=":")
    """
    xmin = np.zeros(y.shape) if xmin is None else np.broadcast_to(xmin, y.shape)
    xmax = np.ones(y.shape) if xmax is None else np.broadcast_to(xmax, y.shape)
    r = get_renderer()
    for yi, xmini, xmaxi in zip(y, xmin, xmax):
        r.horizontal(ax, yi, xmini, xmaxi, **overrides)

    return ax

plot_image

plot_image(values, extent=None, origin='upper', cmap='viridis', vmin=None, vmax=None, colorbar=False, ax=None, spec=None, **overrides)

Display a 2-D array as an image (heatmap), backend-agnostically.

Parameters:

Name Type Description Default
values ndarray

2-D array of scalar values, mapped to colour via cmap.

required
extent Optional[tuple]

(xmin, xmax, ymin, ymax) placement in data coordinates. Defaults to (0, ncols, 0, nrows).

None
origin str

"upper" (row 0 at top, matplotlib default) or "lower".

'upper'
cmap str

matplotlib colormap name; converted to a palette on bokeh so the same name looks the same on every backend.

'viridis'
vmin, vmax

colour-scale limits. Default to the data min/max.

required
colorbar bool | str | ColorbarSpec

add a colorbar. True for a default bar, a str for a labelled bar, or a ColorbarSpec for full control. The mappable is threaded internally — no need to capture it yourself.

False
ax Optional[BehavizAxes]

axes/figure to draw on (created if None).

None
spec Optional[PlotSpec]

plot specification.

None
**overrides

styling forwarded to the active backend renderer.

{}

Returns:

Type Description
(fig, ax)

backend figure and axes handles.

Raises:

Type Description
BehavizDataError

if values is not a numeric 2-D array.

Example

bv.plot_image(correlation_matrix, cmap="magma", colorbar="r")

Source code in behaviz/core/core.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
@plot_function(
    default_spec=DEFAULT_SPEC,
    channels=[Channel("values", kind="grid")],
)
def plot_image(
    values: np.ndarray,
    extent: Optional[tuple] = None,
    origin: str = "upper",
    cmap: str = "viridis",
    vmin: Optional[float] = None,
    vmax: Optional[float] = None,
    colorbar: bool | str | ColorbarSpec = False,
    ax: Optional[BehavizAxes] = None,
    spec: Optional[PlotSpec] = None,
    **overrides,
) -> tuple[BehavizFigure, BehavizAxes]:
    """Display a 2-D array as an image (heatmap), backend-agnostically.

    Args:
        values: 2-D array of scalar values, mapped to colour via ``cmap``.
        extent: (xmin, xmax, ymin, ymax) placement in data coordinates.
            Defaults to (0, ncols, 0, nrows).
        origin: "upper" (row 0 at top, matplotlib default) or "lower".
        cmap: matplotlib colormap name; converted to a palette on bokeh so the
            same name looks the same on every backend.
        vmin, vmax: colour-scale limits. Default to the data min/max.
        colorbar: add a colorbar. ``True`` for a default bar, a ``str`` for a
            labelled bar, or a ``ColorbarSpec`` for full control. The mappable
            is threaded internally — no need to capture it yourself.
        ax: axes/figure to draw on (created if None).
        spec: plot specification.
        **overrides: styling forwarded to the active backend renderer.

    Returns:
        (fig, ax): backend figure and axes handles.

    Raises:
        BehavizDataError: if ``values`` is not a numeric 2-D array.

    Example:
        >>> bv.plot_image(correlation_matrix, cmap="magma", colorbar="r")
    """
    r = get_renderer()
    mappable = r.image(ax, values, extent=extent, origin=origin, cmap=cmap, vmin=vmin, vmax=vmax, **overrides)

    if colorbar:
        r.colorbar(ax, mappable, ColorbarSpec.coerce(colorbar))
    return ax

plot_fill_between

plot_fill_between(x, y1, y2=0, ax=None, spec=None, **overrides)

Fill the band between two curves — e.g. an SEM/CI ribbon, or an area fill.

Parameters:

Name Type Description Default
x ndarray

x values, shape (N,). Array-like, or a column name when data= is given.

required
y1 ndarray

upper curve, shape (N,) (or a scalar for a constant level).

required
y2 float | ndarray

lower curve, shape (N,); a scalar (default 0) fills down to a constant.

0
data

optional dataframe-like the string channels are resolved against.

required
ax Optional[BehavizAxes]

axes to plot on (created if None).

None
spec Optional[PlotSpec]

plot specification.

None
**overrides

styling forwarded to the active backend renderer (e.g. color, alpha).

{}

Returns:

Type Description
(fig, ax)

backend figure and axes handles.

Raises:

Type Description
BehavizDataError

if shapes or types are inconsistent.

Example

bv.plot_fill_between(t, mean - sem, mean + sem, alpha=0.3)

Source code in behaviz/core/core.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
@plot_function(
    default_spec=DEFAULT_SPEC,
    channels=[
        Channel("x"),
        Channel("y1", kind="scalar_or_vector", same_length_as="x"),
        Channel("y2", kind="scalar_or_vector", required=False, same_length_as="x"),
    ],
    grouping="overlay",
)
def plot_fill_between(
    x: np.ndarray,
    y1: np.ndarray,
    y2: float | np.ndarray = 0,
    ax: Optional[BehavizAxes] = None,
    spec: Optional[PlotSpec] = None,
    **overrides,
) -> tuple[BehavizFigure, BehavizAxes]:
    """Fill the band between two curves — e.g. an SEM/CI ribbon, or an area fill.

    Args:
        x: x values, shape (N,). Array-like, or a column name when ``data=``
            is given.
        y1: upper curve, shape (N,) (or a scalar for a constant level).
        y2: lower curve, shape (N,); a scalar (default 0) fills down to a
            constant.
        data: optional dataframe-like the string channels are resolved against.
        ax: axes to plot on (created if None).
        spec: plot specification.
        **overrides: styling forwarded to the active backend renderer
            (e.g. ``color``, ``alpha``).

    Returns:
        (fig, ax): backend figure and axes handles.

    Raises:
        BehavizDataError: if shapes or types are inconsistent.

    Example:
        >>> bv.plot_fill_between(t, mean - sem, mean + sem, alpha=0.3)
    """
    # Broadcast so scalar levels become arrays — bokeh's varea needs arrays.
    y1 = np.broadcast_to(y1, x.shape).astype(float)
    y2 = np.broadcast_to(y2, x.shape).astype(float)

    r = get_renderer()
    r.fill_between(ax, x, y1, y2, **overrides)
    return ax

plot_pie

plot_pie(sizes, labels=None, colors=None, autopct=None, ax=None, spec=None, **overrides)

Pie chart for showing ratios / proportions.

Parameters:

Name Type Description Default
sizes ndarray

slice sizes, shape (N,) — they need not sum to 1, they are normalised. Array-like, or a column name when data= is given.

required
labels Optional[list]

per-slice labels (length N).

None
colors Optional[list]

per-slice colours (defaults to a categorical palette).

None
autopct Optional[str]

percentage format string, e.g. "%.1f%%" (matplotlib/seaborn only).

None
data

optional dataframe-like the string channel is resolved against.

required
ax Optional[BehavizAxes]

axes to plot on (created if None).

None
spec Optional[PlotSpec]

plot specification.

None
**overrides

styling forwarded to the active backend renderer.

{}

Returns:

Type Description
(fig, ax)

backend figure and axes handles.

Raises:

Type Description
BehavizDataError

if sizes is not a numeric 1-D sequence.

Example

bv.plot_pie([40, 35, 25], labels=["go", "no-go", "miss"])

Source code in behaviz/core/core.py
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
@plot_function(
    default_spec=PIE_SPEC,
    channels=[Channel("sizes")],
)
def plot_pie(
    sizes: np.ndarray,
    labels: Optional[list] = None,
    colors: Optional[list] = None,
    autopct: Optional[str] = None,
    ax: Optional[BehavizAxes] = None,
    spec: Optional[PlotSpec] = None,
    **overrides,
) -> tuple[BehavizFigure, BehavizAxes]:
    """Pie chart for showing ratios / proportions.

    Args:
        sizes: slice sizes, shape (N,) — they need not sum to 1, they are
            normalised. Array-like, or a column name when ``data=`` is given.
        labels: per-slice labels (length N).
        colors: per-slice colours (defaults to a categorical palette).
        autopct: percentage format string, e.g. ``"%.1f%%"``
            (matplotlib/seaborn only).
        data: optional dataframe-like the string channel is resolved against.
        ax: axes to plot on (created if None).
        spec: plot specification.
        **overrides: styling forwarded to the active backend renderer.

    Returns:
        (fig, ax): backend figure and axes handles.

    Raises:
        BehavizDataError: if ``sizes`` is not a numeric 1-D sequence.

    Example:
        >>> bv.plot_pie([40, 35, 25], labels=["go", "no-go", "miss"])
    """
    sizes = sizes.astype(float)
    r = get_renderer()
    r.pie(ax, sizes, labels=labels, colors=colors, autopct=autopct, **overrides)
    return ax

plot_hexbin

plot_hexbin(x, y, gridsize=30, cmap='viridis', colorbar=False, ax=None, spec=None, **overrides)

2-D histogram of point data, binned into hexagons and coloured by count.

Unlike plot_image (which displays a pre-computed grid), plot_hexbin bins raw (x, y) points — use it for density / 2-D-histogram views of scatter-like data.

Parameters:

Name Type Description Default
x ndarray

point x coordinates, shape (N,). Array-like, or a column name when data= is given.

required
y ndarray

point y coordinates, shape (N,). Same accepted types as x.

required
gridsize int

number of hexagons across the x-range.

30
cmap str

matplotlib colormap name (converted to a palette on bokeh).

'viridis'
colorbar bool | str | ColorbarSpec

add a count colorbar — True / str / ColorbarSpec.

False
data

optional dataframe-like the string channels are resolved against.

required
ax Optional[BehavizAxes]

axes to plot on (created if None).

None
spec Optional[PlotSpec]

plot specification.

None
**overrides

styling forwarded to the active backend renderer.

{}

Returns:

Type Description
(fig, ax)

backend figure and axes handles.

Raises:

Type Description
BehavizDataError

if shapes or types are inconsistent.

Example

bv.plot_hexbin("rt", "accuracy", data=df, colorbar="trials")

Source code in behaviz/core/core.py
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
@plot_function(
    default_spec=DEFAULT_SPEC,
    channels=[
        Channel("x"),
        Channel("y", same_length_as="x"),
    ],
)
def plot_hexbin(
    x: np.ndarray,
    y: np.ndarray,
    gridsize: int = 30,
    cmap: str = "viridis",
    colorbar: bool | str | ColorbarSpec = False,
    ax: Optional[BehavizAxes] = None,
    spec: Optional[PlotSpec] = None,
    **overrides,
) -> tuple[BehavizFigure, BehavizAxes]:
    """2-D histogram of point data, binned into hexagons and coloured by count.

    Unlike ``plot_image`` (which displays a pre-computed grid), ``plot_hexbin``
    bins raw ``(x, y)`` points — use it for density / 2-D-histogram views of
    scatter-like data.

    Args:
        x: point x coordinates, shape (N,). Array-like, or a column name when
            ``data=`` is given.
        y: point y coordinates, shape (N,). Same accepted types as ``x``.
        gridsize: number of hexagons across the x-range.
        cmap: matplotlib colormap name (converted to a palette on bokeh).
        colorbar: add a count colorbar — ``True`` / ``str`` / ``ColorbarSpec``.
        data: optional dataframe-like the string channels are resolved against.
        ax: axes to plot on (created if None).
        spec: plot specification.
        **overrides: styling forwarded to the active backend renderer.

    Returns:
        (fig, ax): backend figure and axes handles.

    Raises:
        BehavizDataError: if shapes or types are inconsistent.

    Example:
        >>> bv.plot_hexbin("rt", "accuracy", data=df, colorbar="trials")
    """
    x = x.astype(float)
    y = y.astype(float)

    r = get_renderer()
    mappable = r.hexbin(ax, x, y, gridsize=gridsize, cmap=cmap, **overrides)

    if colorbar:
        r.colorbar(ax, mappable, ColorbarSpec.coerce(colorbar))

    return ax

behaviz.core.core_factory