Skip to content

voronoi

Short Description

sm.pl.voronoi: This function enables the visualization of spatial data through the creation of Voronoi diagrams, offering a distinctive method to explore the spatial distribution of cells or features within a defined area. Users can color these diagrams according to values from any categorical column in their dataset, such as cell type or tissue compartment, particularly good looking for manuscripts.

Key considerations for optimal use of this function include:

  • Application Scope: Voronoi diagrams are particularly effective for analyzing small to moderately sized spatial regions, supporting regions with up to 5,000 cells. This constraint ensures both interpretability and performance are maintained, as larger regions can result in complex visualizations that are difficult to interpret and may require extended processing times.

  • Performance and Interpretability: While Voronoi diagrams offer insightful visualizations for spatial data, their utility diminishes with increasing dataset size. For regions containing more than 5,000 cells, the generated plots may become cluttered and challenging to interpret, alongside experiencing significant delays in generation time. Users are encouraged to segment larger datasets into smaller, manageable regions or utilize alternative visualization methods suitable for high-density spatial data.

Function

voronoi(adata, color_by=None, colors=None, x_coordinate='X_centroid', y_coordinate='Y_centroid', imageid='imageid', subset=None, x_lim=None, y_lim=None, flip_y=True, voronoi_edge_color='black', voronoi_line_width=0.1, voronoi_alpha=0.5, size_max=np.inf, overlay_points=None, overlay_points_categories=None, overlay_drop_categories=None, overlay_points_colors=None, overlay_point_size=5, overlay_point_alpha=1, overlay_point_shape='.', plot_legend=True, fileName='voronoi.pdf', saveDir=None, legend_size=6, **kwargs)

Parameters:

Name Type Description Default
adata AnnData

An AnnData object containing the spatial data to be visualized.

required
color_by str

The name of the column used to color the Voronoi diagram. Typically, this column represents categorical variables such as cell types or tissue compartments.

None
colors str or Dict

Custom color mapping for the Voronoi diagram. Can be specified as a seaborn color palette name or a dictionary mapping categories to colors.

None
x_coordinate str

The column name containing the x-coordinates.

'X_centroid'
y_coordinate str

The column name containing the y-coordinates.

'Y_centroid'
imageid str

The column name containing identifiers for different images or spatial contexts.

'imageid'
subset str

Specifies the identifier of a single image to focus the visualization on.

None
x_lim list

The x-axis limits for the plot as a list of two elements: [xmin, xmax].

None
y_lim list

The y-axis limits for the plot as a list of two elements: [ymin, ymax].

None
flip_y bool

If set to True, the y-axis will be flipped. This may be necessary for some datasets where y-coordinates are inverted.

True
voronoi_edge_color str

The color of the edges of the Voronoi cells.

'black'
voronoi_line_width float

The line width of the Voronoi cell edges.

0.1
voronoi_alpha float

The opacity of the Voronoi cells, ranging from 0 (completely transparent) to 1 (completely opaque).

0.5
size_max float

The maximum size for the Voronoi cells. Can be used to limit the cell size in the visualization.

inf
overlay_points str

The name of the column to use for overlaying points on the Voronoi diagram.

None
overlay_points_categories list

Specific categories within the overlay_points column to include in the overlay.

None
overlay_drop_categories list

Specific categories within the overlay_points column to exclude from the overlay.

None
overlay_points_colors str or Dict

Custom color mapping for the overlay points. Can be specified as a seaborn color palette name or a dictionary mapping categories to colors.

None
overlay_point_size float

The size of the overlay points.

5
overlay_point_alpha float

The opacity of the overlay points, ranging from 0 (completely transparent) to 1 (completely opaque).

1
overlay_point_shape str

The shape of the overlay points.

'.'
plot_legend bool

Whether to display a legend for the plot.

True
fileName str

Name of the file to save the plot. Relevant only if saveDir is not None.

'voronoi.pdf'
saveDir str

Directory to save the generated plot. If None, the plot is not saved.

None
legend_size float

The font size of the legend text.

6

Returns:

Name Type Description
Plot matplotlib

Returns a plot.

Example
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#E xample 1: Basic Voronoi plot with default settings

sm.pl.voronoi(adata)


# Example 2: Voronoi plot colored by cell type, with customized colors and overlay points for a specific phenotype

sm.pl.voronoi(adata, color_by='cell_type', colors='Set2', overlay_points='phenotype', overlay_points_colors={'phenotype1': 'red', 'phenotype2': 'blue'}, plot_legend=True)


# Example 3: Voronoi plot for a specific image subset, with adjusted alpha and line width, and without flipping the y-axis

sm.pl.voronoi(adata, subset='image_01', voronoi_alpha=0.7, voronoi_line_width=0.5)
Source code in scimap/plotting/voronoi.py
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
164
165
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
203
204
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
259
260
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
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
374
375
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
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
464
465
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
def voronoi(
    adata,
    color_by=None,
    colors=None,
    x_coordinate='X_centroid',
    y_coordinate='Y_centroid',
    imageid='imageid',
    subset=None,
    x_lim=None,
    y_lim=None,
    flip_y=True,
    voronoi_edge_color='black',
    voronoi_line_width=0.1,
    voronoi_alpha=0.5,
    size_max=np.inf,
    overlay_points=None,
    overlay_points_categories=None,
    overlay_drop_categories=None,
    overlay_points_colors=None,
    overlay_point_size=5,
    overlay_point_alpha=1,
    overlay_point_shape=".",
    plot_legend=True,
    fileName='voronoi.pdf',
    saveDir=None,
    legend_size=6,
    **kwargs,
):
    """
    Parameters:
            adata (anndata.AnnData):
                An AnnData object containing the spatial data to be visualized.

            color_by (str, optional):
                The name of the column used to color the Voronoi diagram. Typically, this column represents categorical
                variables such as cell types or tissue compartments.

            colors (str or Dict, optional):
                Custom color mapping for the Voronoi diagram. Can be specified as a seaborn color palette name or a dictionary
                mapping categories to colors.

            x_coordinate (str, optional):
                The column name containing the x-coordinates.

            y_coordinate (str, optional):
                The column name containing the y-coordinates.

            imageid (str, optional):
                The column name containing identifiers for different images or spatial contexts.

            subset (str, optional):
                Specifies the identifier of a single image to focus the visualization on.

            x_lim (list, optional):
                The x-axis limits for the plot as a list of two elements: [xmin, xmax].

            y_lim (list, optional):
                The y-axis limits for the plot as a list of two elements: [ymin, ymax].

            flip_y (bool, optional):
                If set to True, the y-axis will be flipped. This may be necessary for some datasets where y-coordinates are
                inverted.

            voronoi_edge_color (str, optional):
                The color of the edges of the Voronoi cells.

            voronoi_line_width (float, optional):
                The line width of the Voronoi cell edges.

            voronoi_alpha (float, optional):
                The opacity of the Voronoi cells, ranging from 0 (completely transparent) to 1 (completely opaque).

            size_max (float, optional):
                The maximum size for the Voronoi cells. Can be used to limit the cell size in the visualization.

            overlay_points (str, optional):
                The name of the column to use for overlaying points on the Voronoi diagram.

            overlay_points_categories (list, optional):
                Specific categories within the `overlay_points` column to include in the overlay.

            overlay_drop_categories (list, optional):
                Specific categories within the `overlay_points` column to exclude from the overlay.

            overlay_points_colors (str or Dict, optional):
                Custom color mapping for the overlay points. Can be specified as a seaborn color palette name or a dictionary
                mapping categories to colors.

            overlay_point_size (float, optional):
                The size of the overlay points.

            overlay_point_alpha (float, optional):
                The opacity of the overlay points, ranging from 0 (completely transparent) to 1 (completely opaque).

            overlay_point_shape (str, optional):
                The shape of the overlay points.

            plot_legend (bool, optional):
                Whether to display a legend for the plot.

            fileName (str, optional):
                Name of the file to save the plot. Relevant only if `saveDir` is not None.

            saveDir (str, optional):
                Directory to save the generated plot. If None, the plot is not saved.

            legend_size (float, optional):
                The font size of the legend text.

    Returns:
            Plot (matplotlib):
                    Returns a plot.

    Example:
            ```python


            #E xample 1: Basic Voronoi plot with default settings

            sm.pl.voronoi(adata)


            # Example 2: Voronoi plot colored by cell type, with customized colors and overlay points for a specific phenotype

            sm.pl.voronoi(adata, color_by='cell_type', colors='Set2', overlay_points='phenotype', overlay_points_colors={'phenotype1': 'red', 'phenotype2': 'blue'}, plot_legend=True)


            # Example 3: Voronoi plot for a specific image subset, with adjusted alpha and line width, and without flipping the y-axis

            sm.pl.voronoi(adata, subset='image_01', voronoi_alpha=0.7, voronoi_line_width=0.5)

            ```

    """

    # create the data frame needed
    data = adata.obs.copy()

    # Subset the image of interest
    if subset is not None:
        data = data[data[imageid] == subset]

    # subset coordinates if needed
    if x_lim is not None:
        x1 = x_lim[0]
        if len(x_lim) < 2:
            x2 = max(data[x_coordinate])
        else:
            x2 = x_lim[1]
    if y_lim is not None:
        y1 = y_lim[0]
        if len(y_lim) < 2:
            y2 = min(data[y_coordinate])
        else:
            y2 = y_lim[1]

    # do the actuall subsetting
    # if x_lim is not None:
    #    data = data[data[x_coordinate] >= x1]
    #    data = data[data[x_coordinate] <= x2]
    # if y_lim is not None:
    #    data = data[data[y_coordinate] <= y1]
    #    data = data[data[y_coordinate] >= y2]

    # do the actuall subsetting
    if x_lim is not None:
        data = data[(data[x_coordinate] >= x1) & (data[x_coordinate] <= x2)]
    if y_lim is not None:
        data = data[(data[y_coordinate] >= y1) & (data[y_coordinate] <= y2)]

    # create an extra column with index information
    data['index_info'] = np.arange(data.shape[0])

    # generate the x and y coordinates
    points = data[[x_coordinate, y_coordinate]].values

    # invert the Y-axis
    if flip_y is True:
        points[:, 1] = max(points[:, 1]) - points[:, 1]

    # Generate colors
    if color_by is None:
        colors = np.repeat('#e5e5e5', len(data))
    #    elif color_by is None and colors is not None:
    #        if isinstance(colors,str):
    #            colors = np.repeat(colors, len(data))
    elif color_by is not None and colors is None:
        # auto color the samples
        if len(np.unique(data[color_by])) <= 9:
            c = sns.color_palette('Set1')[0 : len(np.unique(data[color_by]))]
        if len(np.unique(data[color_by])) > 9 and len(np.unique(data[color_by])) <= 20:
            c = sns.color_palette('tab20')[0 : len(np.unique(data[color_by]))]
        if len(np.unique(data[color_by])) > 20:
            # For large categories generate random colors
            np.random.seed(0)
            c = np.random.rand(len(np.unique(data[color_by])), 3).tolist()
        # merge colors with phenotypes/ categories of interest
        p = np.unique(data[color_by])
        c_p = dict(zip(p, c))
        # map to colors
        colors = list(map(c_p.get, list(data[color_by].values)))
    elif color_by is not None and colors is not None:
        # check if colors is a dictionary or a sns color scale
        if isinstance(colors, str):
            if len(sns.color_palette(colors)) < len(np.unique(data[color_by])):
                raise ValueError(
                    str(colors)
                    + ' includes a maximun of '
                    + str(len(sns.color_palette(colors)))
                    + ' colors, while your data need '
                    + str(len(np.unique(data[color_by])))
                    + ' colors'
                )
            else:
                c = sns.color_palette(colors)[0 : len(np.unique(data[color_by]))]
                # merge colors with phenotypes/ categories of interest
                p = np.unique(data[color_by])
                c_p = dict(zip(p, c))
        if isinstance(colors, dict):
            if len(colors) < len(np.unique(data[color_by])):
                raise ValueError(
                    'Color mapping is not provided for all categories. Please check'
                )
            else:
                c_p = colors
        # map to colors
        colors = list(map(c_p.get, list(data[color_by].values)))

    # create the voronoi object
    vor = Voronoi(points)

    # trim the object
    regions, vertices = voronoi_finite_polygons_2d(vor)

    # plotting
    pts = MultiPoint([Point(i) for i in points])
    mask = pts.convex_hull
    new_vertices = []
    if type(voronoi_alpha) != list:
        voronoi_alpha = [voronoi_alpha] * len(points)
    areas = []
    for i, (region, alph) in enumerate(zip(regions, voronoi_alpha)):
        polygon = vertices[region]
        shape = list(polygon.shape)
        shape[0] += 1
        p = Polygon(np.append(polygon, polygon[0]).reshape(*shape)).intersection(mask)
        areas += [p.area]
        if p.area < size_max:
            poly = np.array(
                list(zip(p.boundary.coords.xy[0][:-1], p.boundary.coords.xy[1][:-1]))
            )
            new_vertices.append(poly)
            if voronoi_edge_color == 'facecolor':
                plt.fill(
                    *zip(*poly),
                    alpha=alph,
                    edgecolor=colors[i],
                    linewidth=voronoi_line_width,
                    facecolor=colors[i],
                )
                plt.xticks([])
                plt.yticks([])
            else:
                plt.fill(
                    *zip(*poly),
                    alpha=alph,
                    edgecolor=voronoi_edge_color,
                    linewidth=voronoi_line_width,
                    facecolor=colors[i],
                )
                plt.xticks([])
                plt.yticks([])
                # plt.xlim([1097.5,1414.5])
                # plt.ylim([167.3,464.1])

    # Add scatter on top of the voronoi if user requests
    if overlay_points is not None:
        if overlay_points_categories is None:
            d = data
        if overlay_points_categories is not None:
            # convert to list if needed (cells to keep)
            if isinstance(overlay_points_categories, str):
                overlay_points_categories = [overlay_points_categories]
            # subset cells needed
            d = data[data[overlay_points].isin(overlay_points_categories)]
        if overlay_drop_categories is not None:
            # conver to list if needed (cells to drop)
            if isinstance(overlay_drop_categories, str):
                overlay_drop_categories = [overlay_drop_categories]
            # subset cells needed
            d = d[-d[overlay_points].isin(overlay_drop_categories)]

        # Find the x and y coordinates for the overlay category
        # points_scatter = d[[x_coordinate,y_coordinate]].values
        points_scatter = points[d.index_info.values]

        # invert the Y-axis
        # points_scatter[:,1] = max(points_scatter[:,1])-points_scatter[:,1]

        # Generate colors for the scatter plot
        if overlay_points_colors is None and color_by == overlay_points:
            # Borrow color from vornoi
            wanted_keys = np.unique(d[overlay_points])  # The keys to extract
            c_p_scatter = dict((k, c_p[k]) for k in wanted_keys if k in c_p)
        elif overlay_points_colors is None and color_by != overlay_points:
            # Randomly generate colors for all the categories in scatter plot
            # auto color the samples
            if len(np.unique(d[overlay_points])) <= 9:
                c_scatter = sns.color_palette('Set1')[
                    0 : len(np.unique(d[overlay_points]))
                ]
            if (
                len(np.unique(d[overlay_points])) > 9
                and len(np.unique(d[overlay_points])) <= 20
            ):
                c_scatter = sns.color_palette('tab20')[
                    0 : len(np.unique(d[overlay_points]))
                ]
            if len(np.unique(d[overlay_points])) > 20:
                # For large categories generate random colors
                np.random.seed(1)
                c_scatter = np.random.rand(
                    len(np.unique(d[overlay_points])), 3
                ).tolist()
            # merge colors with phenotypes/ categories of interest
            p_scatter = np.unique(d[overlay_points])
            c_p_scatter = dict(zip(p_scatter, c_scatter))
        elif overlay_points_colors is not None:
            # check if the overlay_points_colors is a pallete
            if isinstance(overlay_points_colors, str):
                try:
                    c_scatter = sns.color_palette(overlay_points_colors)[
                        0 : len(np.unique(d[overlay_points]))
                    ]
                    if len(sns.color_palette(overlay_points_colors)) < len(
                        np.unique(d[overlay_points])
                    ):
                        raise ValueError(
                            str(overlay_points_colors)
                            + ' pallete includes a maximun of '
                            + str(len(sns.color_palette(overlay_points_colors)))
                            + ' colors, while your data (overlay_points_colors) need '
                            + str(len(np.unique(d[overlay_points])))
                            + ' colors'
                        )
                except:
                    c_scatter = np.repeat(
                        overlay_points_colors, len(np.unique(d[overlay_points]))
                    )  # [overlay_points_colors]
                # create a dict
                p_scatter = np.unique(d[overlay_points])
                c_p_scatter = dict(zip(p_scatter, c_scatter))
            if isinstance(overlay_points_colors, dict):
                if len(overlay_points_colors) < len(np.unique(d[overlay_points])):
                    raise ValueError(
                        'Color mapping is not provided for all categories. Please check overlay_points_colors'
                    )
                else:
                    c_p_scatter = overlay_points_colors
        # map to colors
        colors_scatter = list(map(c_p_scatter.get, list(d[overlay_points].values)))

        # plt.scatter(x = points_scatter[:,0], y = points_scatter[:,1], s= overlay_point_size, alpha= overlay_point_alpha, c= colors_scatter, marker=overlay_point_shape)
        plt.scatter(
            x=points_scatter[:, 0],
            y=points_scatter[:, 1],
            s=overlay_point_size,
            alpha=overlay_point_alpha,
            c=colors_scatter,
            marker=overlay_point_shape,
            **kwargs,
        )
        plt.xticks([])
        plt.yticks([])

    if plot_legend is True:
        # Add legend to voronoi
        patchList = []
        for key in c_p:
            data_key = mpatches.Patch(color=c_p[key], label=key)
            patchList.append(data_key)

        first_legend = plt.legend(
            handles=patchList,
            bbox_to_anchor=(1.05, 1),
            loc=2,
            borderaxespad=0.0,
            prop={'size': legend_size},
        )

        try:
            plt.tight_layout()
        except:
            pass

        # Add the legend manually to the current Axes.
        ax = plt.gca().add_artist(first_legend)

        if overlay_points is not None:
            # Add legend to scatter
            patchList_scatter = []
            for key in c_p_scatter:
                data_key_scatter = mpatches.Patch(color=c_p_scatter[key], label=key)
                patchList_scatter.append(data_key_scatter)

            plt.legend(
                handles=patchList_scatter,
                bbox_to_anchor=(-0.05, 1),
                loc=1,
                borderaxespad=0.0,
                prop={'size': legend_size},
            )
            # plt.tight_layout()

    # Saving the figure if saveDir and fileName are provided
    if saveDir:
        if not os.path.exists(saveDir):
            os.makedirs(saveDir)
        full_path = os.path.join(saveDir, fileName)
        plt.savefig(full_path, dpi=300)
        plt.close()
        print(f"Saved plot to {full_path}")
    else:
        plt.show()