Skip to content

slisemap.plot

Utility functions for plotting.

legend_inside_facet(grid)

Move the legend to within the facet grid if possible.

Parameters:

Name Type Description Default
grid FacetGrid

Facet grid

required
Source code in slisemap/plot.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
def legend_inside_facet(grid: sns.FacetGrid) -> None:
    """Move the legend to within the facet grid if possible.

    Args:
        grid: Facet grid
    """
    col_wrap = grid._col_wrap
    facets = grid._n_facets
    if col_wrap < facets and facets % col_wrap != 0:
        w = 1 / col_wrap
        h = 1 / ((facets - 1) // col_wrap + 1)
        sns.move_legend(
            grid,
            "center",
            bbox_to_anchor=(1 - w, h * 0.1, w * 0.9, h * 0.9),
            frameon=False,
        )
        plt.tight_layout()

plot_embedding(Z, dimensions=('SLISEMAP 1', 'SLISEMAP 2'), title='Embedding', jitter=0.0, clusters=None, color=None, color_name='', color_norm=None, **kwargs)

Plot an embedding in a scatterplot.

Parameters:

Name Type Description Default
Z ndarray

The embedding.

required
dimensions Sequence[str]

Dimension names. Defaults to ("SLISEMAP 1", "SLISEMAP 2").

('SLISEMAP 1', 'SLISEMAP 2')
title str

Plot title. Defaults to "Embedding".

'Embedding'
jitter Union[float, ndarray]

Jitter amount. Defaults to 0.0.

0.0
clusters Optional[Sequence[int]]

Cluster labels. Defaults to None.

None
color Optional[Sequence[float]]

Variable for coloring. Defaults to None.

None
color_name str

Variable name. Defaults to "".

''
color_norm Optional[Tuple[float]]

Color scale limits. Defaults to None.

None

Other Parameters:

Name Type Description
**kwargs Any

Additional arguments to seaborn.scatterplot.

Returns:

Type Description
Axes

The plot.

Source code in slisemap/plot.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
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
def plot_embedding(
    Z: np.ndarray,
    dimensions: Sequence[str] = ("SLISEMAP 1", "SLISEMAP 2"),
    title: str = "Embedding",
    jitter: Union[float, np.ndarray] = 0.0,
    clusters: Optional[Sequence[int]] = None,
    color: Optional[Sequence[float]] = None,
    color_name: str = "",
    color_norm: Optional[Tuple[float]] = None,
    **kwargs: Any,
) -> plt.Axes:
    """Plot an embedding in a scatterplot.

    Args:
        Z: The embedding.
        dimensions: Dimension names. Defaults to ("SLISEMAP 1", "SLISEMAP 2").
        title: Plot title. Defaults to "Embedding".
        jitter: Jitter amount. Defaults to 0.0.
        clusters: Cluster labels. Defaults to None.
        color: Variable for coloring. Defaults to None.
        color_name: Variable name. Defaults to "".
        color_norm: Color scale limits. Defaults to None.

    Keyword Args:
        **kwargs: Additional arguments to `seaborn.scatterplot`.

    Returns:
        The plot.
    """
    Z, dimensions = _prepare_Z(Z, dimensions, jitter, plot_embedding)
    kwargs.setdefault("rasterized", Z.shape[0] > 2_000)
    if clusters is None:
        kwargs.setdefault("palette", "crest")
        if color is not None:
            ax = sns.scatterplot(
                x=Z[:, 0],
                y=Z[:, 1],
                hue=color,
                hue_norm=color_norm,
                legend=False,
                **kwargs,
            )
        else:
            ax = sns.scatterplot(x=Z[:, 0], y=Z[:, 1], **kwargs)
    else:
        kwargs.setdefault("palette", "bright")
        ax = sns.scatterplot(
            x=Z[:, 0], y=Z[:, 1], hue=clusters, style=clusters, **kwargs
        )
        color_name = "Cluster"
    if color_norm is not None:
        ax.legend(*_create_legend(color_norm, kwargs["palette"], 5), title=color_name)
    elif color_name is not None and color_name != "":
        ax.legend(title=color_name)
    ax.set_xlabel(dimensions[0])
    ax.set_ylabel(dimensions[1])
    ax.axis("equal")
    ax.set_title(title)
    return ax

plot_matrix(B, coefficients, title='Local models', palette='RdBu', xlabel='Data items sorted left to right', items=None, **kwargs)

Plot local models in a heatmap.

Parameters:

Name Type Description Default
B ndarray

Local model coefficients.

required
coefficients Sequence[str]

Coefficient names.

required
palette str

seaborn palette. Defaults to "RdBu".

'RdBu'
title str

Title of the plot. Defaults to "Local models".

'Local models'
xlabel str

Label for the x-axis. Defaults to "Data items sorted left to right".

'Data items sorted left to right'
items Optional[Sequence[str]]

Ticklabels for the x-axis. Defaults to None.

None

Other Parameters:

Name Type Description
**kwargs Any

Additional arguments to seaborn.heatmap.

Returns:

Type Description
Axes

The plot.

Source code in slisemap/plot.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def plot_matrix(
    B: np.ndarray,
    coefficients: Sequence[str],
    title: str = "Local models",
    palette: str = "RdBu",
    xlabel: str = "Data items sorted left to right",
    items: Optional[Sequence[str]] = None,
    **kwargs: Any,
) -> plt.Axes:
    """Plot local models in a heatmap.

    Args:
        B: Local model coefficients.
        coefficients: Coefficient names.
        palette: `seaborn` palette. Defaults to "RdBu".
        title: Title of the plot. Defaults to "Local models".
        xlabel: Label for the x-axis. Defaults to "Data items sorted left to right".
        items: Ticklabels for the x-axis. Defaults to None.

    Keyword Args:
        **kwargs: Additional arguments to `seaborn.heatmap`.

    Returns:
        The plot.
    """
    kwargs.setdefault("rasterized", B.shape[0] * B.shape[1] > 20_000)
    ax = sns.heatmap(B.T, center=0, cmap=palette, robust=True, **kwargs)
    ax.set_yticks(np.arange(len(coefficients)) + 0.5)
    ax.set_yticklabels(coefficients, rotation=0)
    ax.set_xlabel(xlabel)
    if items is None:
        ax.set_xticklabels([])
    else:
        ax.set_xticks(np.arange(len(items)) + 0.5)
        ax.set_xticklabels(items)
    ax.set_title(title)
    return ax

plot_barmodels(B, clusters, centers, coefficients, bars=True, palette='bright', xlabel='Coefficients', title='Cluster mean local model', **kwargs)

Plot local models in a barplot.

Parameters:

Name Type Description Default
B ndarray

Local model coefficients.

required
clusters ndarray

Cluster labels.

required
centers ndarray

Cluster centers.

required
coefficients Sequence[str]

Coefficient names.

required
bars Union[bool, int, Sequence[str]]

Number / list of variables to show (or a bool for all). Defaults to True.

True
palette str

seaborn palette. Defaults to "bright".

'bright'
xlabel Optional[str]

Label for the x-axis. Defaults to "Coefficients".

'Coefficients'
title Optional[str]

Title of the plot. Defaults to "Cluster mean local model".

'Cluster mean local model'

Other Parameters:

Name Type Description
**kwargs Any

Additional arguments to seaborn.barplot.

Returns:

Type Description
Axes

The plot.

Source code in slisemap/plot.py
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
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
def plot_barmodels(
    B: np.ndarray,
    clusters: np.ndarray,
    centers: np.ndarray,
    coefficients: Sequence[str],
    bars: Union[bool, int, Sequence[str]] = True,
    palette: str = "bright",
    xlabel: Optional[str] = "Coefficients",
    title: Optional[str] = "Cluster mean local model",
    **kwargs: Any,
) -> plt.Axes:
    """Plot local models in a barplot.

    Args:
        B: Local model coefficients.
        clusters: Cluster labels.
        centers: Cluster centers.
        coefficients: Coefficient names.
        bars: Number / list of variables to show (or a bool for all). Defaults to True.
        palette: `seaborn` palette. Defaults to "bright".
        xlabel: Label for the x-axis. Defaults to "Coefficients".
        title: Title of the plot. Defaults to "Cluster mean local model".

    Keyword Args:
        **kwargs: Additional arguments to `seaborn.barplot`.

    Returns:
        The plot.
    """
    if isinstance(bars, Sequence):
        mask = [coefficients.index(var) for var in bars]
        coefficients = bars
        B = B[:, mask]
    elif isinstance(bars, bool):
        pass
    elif isinstance(bars, int):
        influence = np.abs(centers)
        influence = influence.max(0) + influence.mean(0)
        mask = np.argsort(-influence)[:bars]
        coefficients = np.asarray(coefficients)[mask]
        B = B[:, mask]
    kwargs.setdefault("rasterized", B.shape[0] * B.shape[1] > 20_000)
    ax = sns.barplot(
        y=np.tile(coefficients, B.shape[0]),
        x=B.ravel(),
        hue=np.repeat(clusters, B.shape[1]),
        palette=palette,
        orient="h",
        **kwargs,
    )
    ax.legend().remove()
    lim = np.max(np.abs(ax.get_xlim()))
    ax.set(xlabel=xlabel, ylabel=None, title=title, xlim=(-lim, lim))
    return ax

plot_embedding_facet(Z, dimensions, data, names, legend_title='Value', jitter=0.0, share_hue=True, equal_aspect=True, **kwargs)

Plot (multiple) embeddings.

Parameters:

Name Type Description Default
Z ndarray

Embeddings.

required
dimensions Sequence[str]

Dimension names.

required
data ndarray

Data matrix.

required
names Sequence[str]

Column names.

required
legend_title str

Legend title. Defaults to "Value".

'Value'
jitter Union[float, ndarray]

jitter. Defaults to 0.0.

0.0
share_hue bool

Share color legend between facets.

True
equal_aspect bool

Set equal scale for the axes. Defaults to True.

True

Other Parameters:

Name Type Description
**kwargs Any

Additional arguments to seaborn.relplot.

Returns:

Type Description
FacetGrid

The plot.

Source code in slisemap/plot.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
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
324
325
326
327
328
329
330
331
332
333
334
def plot_embedding_facet(
    Z: np.ndarray,
    dimensions: Sequence[str],
    data: np.ndarray,
    names: Sequence[str],
    legend_title: str = "Value",
    jitter: Union[float, np.ndarray] = 0.0,
    share_hue: bool = True,
    equal_aspect: bool = True,
    **kwargs: Any,
) -> sns.FacetGrid:
    """Plot (multiple) embeddings.

    Args:
        Z: Embeddings.
        dimensions: Dimension names.
        data: Data matrix.
        names: Column names.
        legend_title: Legend title. Defaults to "Value".
        jitter: jitter. Defaults to 0.0.
        share_hue: Share color legend between facets.
        equal_aspect: Set equal scale for the axes. Defaults to True.

    Keyword Args:
        **kwargs: Additional arguments to `seaborn.relplot`.

    Returns:
        The plot.
    """
    Z, dimensions = _prepare_Z(Z, dimensions, jitter, plot_embedding_facet)
    df = dict_concat(
        {
            "var": n,
            legend_title: data[:, i],
            dimensions[0]: Z[:, 0],
            dimensions[1]: Z[:, 1],
        }
        for i, n in enumerate(names)
    )
    kwargs.setdefault("palette", "rocket")
    kwargs.setdefault("rasterized", Z.shape[0] > 2_000)
    if share_hue:
        kwargs.setdefault("kind", "scatter")
        g = sns.relplot(
            data=df,
            x=dimensions[0],
            y=dimensions[1],
            hue=legend_title,
            col="var",
            **kwargs,
        )
    else:
        fgkws = kwargs.pop("facet_kws", {})
        fgkws.setdefault("height", 5)
        for k in ("height", "aspect", "col_wrap"):
            if k in kwargs:
                fgkws[k] = kwargs.pop(k)
        fgkws.setdefault("legend_out", False)
        g = sns.FacetGrid(data=df, col="var", hue=legend_title, **fgkws)
        for key, ax in g.axes_dict.items():
            mask = df["var"] == key
            df2 = {k: v[mask] for k, v in df.items()}
            sns.scatterplot(
                data=df2,
                hue=legend_title,
                x=dimensions[0],
                y=dimensions[1],
                ax=ax,
                **kwargs,
            )
    if equal_aspect:
        g.set(aspect="equal")
    g.set_titles("{col_name}")
    return g

plot_density_facet(data, names, clusters=None, **kwargs)

Plot density plots.

Parameters:

Name Type Description Default
data ndarray

Data matrix.

required
names Sequence[str]

Column names.

required
clusters Optional[ndarray]

Cluster labels. Defaults to None.

None

Other Parameters:

Name Type Description
**kwargs Any

Additional arguments to seaborn.displot.

Returns:

Type Description
FacetGrid

The plot.

Source code in slisemap/plot.py
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
374
375
def plot_density_facet(
    data: np.ndarray,
    names: Sequence[str],
    clusters: Optional[np.ndarray] = None,
    **kwargs: Any,
) -> sns.FacetGrid:
    """Plot density plots.

    Args:
        data: Data matrix.
        names: Column names.
        clusters: Cluster labels. Defaults to None.

    Keyword Args:
        **kwargs: Additional arguments to `seaborn.displot`.

    Returns:
        The plot.
    """
    df = dict_concat(
        {"var": n, "Value": data[:, i], "Cluster": clusters}
        for i, n in enumerate(names)
    )
    if kwargs.setdefault("kind", "kde") == "kde":
        kwargs.setdefault("bw_adjust", 0.75)
        kwargs.setdefault("common_norm", False)
    if clusters is not None:
        kwargs.setdefault("palette", "bright")
    kwargs.setdefault("facet_kws", {"sharex": False, "sharey": False})
    g = sns.displot(
        data=df,
        x="Value",
        hue=None if clusters is None else "Cluster",
        col="var",
        **kwargs,
    )
    g.set_titles("{col_name}")
    g.set_xlabels("")
    return g

plot_prototypes(Zp, *axs)

Draw a grid of prototypes.

Parameters:

Name Type Description Default
Zp ndarray

Prototype coordinates.

required
*axs Axes

Axes to draw on.

()
Source code in slisemap/plot.py
378
379
380
381
382
383
384
385
386
387
def plot_prototypes(Zp: np.ndarray, *axs: plt.Axes) -> None:
    """Draw a grid of prototypes.

    Args:
        Zp: Prototype coordinates.
        *axs: Axes to draw on.
    """
    Zp, _ = _prepare_Z(Zp, range(2), 0.0, plot_prototypes)
    for ax in axs:
        ax.scatter(Zp[:, 0], Zp[:, 1], edgecolors="grey", facecolors="none", alpha=0.7)

plot_solution(Z, B, coefficients, dimensions, loss=None, clusters=None, centers=None, title='', bars=True, jitter=0.0, left_kwargs={}, right_kwargs={}, **kwargs)

Plot a Slisemap solution.

Parameters:

Name Type Description Default
Z ndarray

Embedding matrix.

required
B ndarray

Local model coefficients.

required
coefficients Sequence[str]

Coefficient names.

required
dimensions Sequence[str]

Embedding names.

required
loss Optional[ndarray]

Local loss vector. Defaults to None.

None
clusters Optional[ndarray]

Cluster labels. Defaults to None.

None
centers Optional[ndarray]

Cluster centroids. Defaults to None.

None
title str

Plot title. Defaults to "".

''
bars Union[bool, int, Sequence[str]]

Plot coefficients in a barplot instead of a heatmap. Defaults to True.

True
jitter Union[float, ndarray]

Add noise to the embedding. Defaults to 0.0.

0.0
left_kwargs Dict[str, object]

Keyword arguments to the left (embedding) plot. Defaults to {}.

{}
right_kwargs Dict[str, object]

Keyword arguments to the right (matrix/bar) plot. Defaults to {}.

{}

Other Parameters:

Name Type Description
**kwargs Any

Additional arguments to matplotlib.pyplot.subplots.

Returns:

Type Description
Figure

Figure

Source code in slisemap/plot.py
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
423
424
425
426
427
428
429
430
431
432
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
def plot_solution(
    Z: np.ndarray,
    B: np.ndarray,
    coefficients: Sequence[str],
    dimensions: Sequence[str],
    loss: Optional[np.ndarray] = None,
    clusters: Optional[np.ndarray] = None,
    centers: Optional[np.ndarray] = None,
    title: str = "",
    bars: Union[bool, int, Sequence[str]] = True,
    jitter: Union[float, np.ndarray] = 0.0,
    left_kwargs: Dict[str, object] = {},
    right_kwargs: Dict[str, object] = {},
    **kwargs: Any,
) -> figure.Figure:
    """Plot a Slisemap solution.

    Args:
        Z: Embedding matrix.
        B: Local model coefficients.
        coefficients: Coefficient names.
        dimensions: Embedding names.
        loss: Local loss vector. Defaults to None.
        clusters: Cluster labels. Defaults to None.
        centers: Cluster centroids. Defaults to None.
        title: Plot title. Defaults to "".
        bars: Plot coefficients in a barplot instead of a heatmap. Defaults to True.
        jitter: Add noise to the embedding. Defaults to 0.0.
        left_kwargs: Keyword arguments to the left (embedding) plot. Defaults to {}.
        right_kwargs: Keyword arguments to the right (matrix/bar) plot. Defaults to {}.

    Keyword Args:
        **kwargs: Additional arguments to `matplotlib.pyplot.subplots`.

    Returns:
        Figure
    """
    kwargs.setdefault("figsize", (12, 6))
    fig, (ax1, ax2) = plt.subplots(1, 2, **kwargs)
    if clusters is None:
        plot_embedding(
            Z,
            dimensions,
            jitter=jitter,
            color=loss.ravel(),
            color_name=None if loss is None else "Local loss",
            color_norm=None if loss is None else tuple(np.quantile(loss, (0.0, 0.95))),
            ax=ax1,
            **left_kwargs,
        )
        B = B[np.argsort(Z[:, 0])]
        plot_matrix(B, coefficients, ax=ax2, **right_kwargs)
    else:
        plot_embedding(
            Z, dimensions, jitter=jitter, clusters=clusters, ax=ax1, **left_kwargs
        )
        if bars:
            plot_barmodels(
                B, clusters, centers, coefficients, bars=bars, ax=ax2, **right_kwargs
            )
        else:
            plot_matrix(
                centers,
                coefficients,
                title="Cluster mean local model",
                xlabel="Cluster",
                items=np.unique(clusters),
                ax=ax2,
                **right_kwargs,
            )
    sns.despine(fig)
    plt.suptitle(title)
    plt.tight_layout()
    return fig

plot_position(Z, L, Zs, dimensions, title='', jitter=0.0, legend_inside=True, marker_size=1.0, **kwargs)

Plot local losses for alternative locations for the selected item(s).

Parameters:

Name Type Description Default
Z ndarray

Embedding matrix.

required
L ndarray

Loss matrix.

required
Zs Optional[ndarray]

Selected coordinates.

required
dimensions Sequence[str]

Embedding names.

required
title str

Plot title. Defaults to "".

''
jitter Union[float, ndarray]

Add random noise to the embedding. Defaults to 0.0.

0.0
legend_inside bool

Move the legend inside the grid (if there is an empty cell). Defaults to True.

True
marker_size float

Multiply the point size with this value. Defaults to 1.0.

1.0

Other Parameters:

Name Type Description
**kwargs Any

Additional arguments to seaborn.relplot.

Returns:

Type Description
FacetGrid

FacetGrid

Source code in slisemap/plot.py
466
467
468
469
470
471
472
473
474
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
def plot_position(
    Z: np.ndarray,
    L: np.ndarray,
    Zs: Optional[np.ndarray],
    dimensions: Sequence[str],
    title: str = "",
    jitter: Union[float, np.ndarray] = 0.0,
    legend_inside: bool = True,
    marker_size: float = 1.0,
    **kwargs: Any,
) -> sns.FacetGrid:
    """Plot local losses for alternative locations for the selected item(s).

    Args:
        Z: Embedding matrix.
        L: Loss matrix.
        Zs: Selected coordinates.
        dimensions: Embedding names.
        title: Plot title. Defaults to "".
        jitter: Add random noise to the embedding. Defaults to 0.0.
        legend_inside: Move the legend inside the grid (if there is an empty cell). Defaults to True.
        marker_size: Multiply the point size with this value. Defaults to 1.0.

    Keyword Args:
        **kwargs: Additional arguments to `seaborn.relplot`.

    Returns:
        FacetGrid
    """
    kwargs.setdefault("palette", "crest")
    kwargs.setdefault("col_wrap", min(4, L.shape[1]))
    if marker_size != 1.0:
        kwargs.setdefault("s", plt.rcParams["lines.markersize"] * marker_size)
    hue_norm = tuple(np.quantile(L, (0.0, 0.95)))
    g = plot_embedding_facet(
        Z,
        dimensions,
        L,
        range(L.shape[1]),
        legend_title="Local loss",
        hue_norm=hue_norm,
        jitter=jitter,
        legend=False,
        **kwargs,
    )
    g.set_titles("")
    plt.suptitle(title)
    # Legend
    col_wrap = kwargs["col_wrap"]
    facets = g._n_facets
    legend = {s: h for h, s in zip(*_create_legend(hue_norm, kwargs["palette"], 6))}
    inside = legend_inside and col_wrap < facets and facets % col_wrap != 0
    w = 1 / col_wrap
    h = 1 / ((facets - 1) // col_wrap + 1)
    if Zs is not None:
        size = plt.rcParams["lines.markersize"] * 18.0
        for i, ax in enumerate(g.axes.ravel()):
            ax.scatter(Zs[i, 0], Zs[i, 1], size, "#fd8431", "X")
        g.add_legend(
            legend,
            "Local loss",
            loc="lower center" if inside else "upper right",
            bbox_to_anchor=(1 - w, h * 0.35, w * 0.9, h * 0.6) if inside else None,
        )
        marker = Line2D(
            [], [], linestyle="None", color="#fd8431", marker="X", markersize=5
        )
        g.add_legend(
            {"": marker},
            "Selected",
            loc="upper center" if inside else "lower right",
            bbox_to_anchor=(1 - w, h * 0.05, w * 0.9, h * 0.3) if inside else None,
        )
    else:
        g.add_legend(
            legend,
            "Local loss",
            loc="center" if inside else "center right",
            bbox_to_anchor=(1 - w, 0.05, w * 0.9, h * 0.9) if inside else None,
        )
    if inside:
        plt.tight_layout()
    else:
        g.tight_layout()
    return g

plot_dist(X, Y, Z, loss, variables, targets, dimensions, title='', clusters=None, scatter=False, jitter=0.0, legend_inside=True, **kwargs)

Plot the distribution of the variables, either as density plots (with clusters) or as scatterplots.

Parameters:

Name Type Description Default
X ndarray

Data matrix.

required
Y ndarray

Target matrix.

required
Z ndarray

Embedding matrix.

required
loss ndarray

Local loss vector.

required
variables Sequence[str]

Variable names.

required
targets Sequence[str]

Target names.

required
dimensions Sequence[str]

Embedding names.

required
title str

Plot title. Defaults to "".

''
clusters Optional[ndarray]

Cluster labels. Defaults to None.

None
scatter bool

Plot a scatterplot instead of a density plot. Defaults to False.

False
jitter Union[float, ndarray]

Add noise to the embedding. Defaults to 0.0.

0.0
legend_inside bool

Move the legend inside a facet, if possible.. Defaults to True.

True

Other Parameters:

Name Type Description
**kwargs Any

Additional arguments to seaborn.relplot or seaborn.scatterplot.

Returns:

Type Description
FacetGrid

FacetGrid.

Source code in slisemap/plot.py
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
def plot_dist(
    X: np.ndarray,
    Y: np.ndarray,
    Z: np.ndarray,
    loss: np.ndarray,
    variables: Sequence[str],
    targets: Sequence[str],
    dimensions: Sequence[str],
    title: str = "",
    clusters: Optional[np.ndarray] = None,
    scatter: bool = False,
    jitter: Union[float, np.ndarray] = 0.0,
    legend_inside: bool = True,
    **kwargs: Any,
) -> sns.FacetGrid:
    """Plot the distribution of the variables, either as density plots (with clusters) or as scatterplots.

    Args:
        X: Data matrix.
        Y: Target matrix.
        Z: Embedding matrix.
        loss: Local loss vector.
        variables: Variable names.
        targets: Target names.
        dimensions: Embedding names.
        title: Plot title. Defaults to "".
        clusters: Cluster labels. Defaults to None.
        scatter: Plot a scatterplot instead of a density plot. Defaults to False.
        jitter: Add noise to the embedding. Defaults to 0.0.
        legend_inside: Move the legend inside a facet, if possible.. Defaults to True.

    Keyword Args:
        **kwargs: Additional arguments to `seaborn.relplot` or `seaborn.scatterplot`.

    Returns:
        FacetGrid.
    """
    data = np.concatenate((X, Y, loss.ravel()[:, None]), 1)
    labels = variables + targets + ["Local loss"]
    kwargs.setdefault("col_wrap", 4)
    if scatter:
        g = plot_embedding_facet(
            Z, dimensions, data, labels, jitter=jitter, share_hue=False, **kwargs
        )
    else:
        g = plot_density_facet(data, labels, clusters=clusters, **kwargs)
    plt.suptitle(title)
    if scatter or clusters is None or not legend_inside:
        g.tight_layout()
    else:
        legend_inside_facet(g)
    return g