plot_embedding#

SingleCell.plot_embedding(embedding_key, color_column, filename=None, /, *, cells_to_plot_column='passed_QC', ax=None, figure_kwargs=None, point_size=None, sort_by_frequency=False, colormap=None, lightness_range=(33.333333333333336, 66.66666666666667), chroma_range=(50, 100), hue_range=None, first_color='#008cb9', stride=5, default_color='lightgray', scatter_kwargs=None, label=False, label_kwargs=None, legend=True, legend_kwargs=None, colorbar=True, colorbar_kwargs=None, title=None, title_kwargs=None, xlabel='Component 1', xlabel_kwargs=None, ylabel='Component 2', ylabel_kwargs=None, xlim=None, ylim=None, despine=True, savefig_kwargs=None)[source]#

Plot the specified 2D embedding.

Parameters:
  • embedding_key: str

    the key of obsm containing the embedding to plot

  • color_column: SingleCellColumn | None

    an optional column of obs indicating how to color each cell in the plot. Can be a column name, a polars expression, a polars Series, a 1D NumPy array, or a function that takes in this SingleCell dataset and returns a polars Series or 1D NumPy array. Can be discrete (e.g. cell-type labels), specified as a String/Enum/Categorical column, or quantitative (e.g. the number of UMIs per cell), specified as an integer/floating-point column. Missing (null) cells will be plotted with the color default_color. Set to None to use default_color for all cells.

  • filename: str | Path | None

    the file to save to. If None, generate the plot but do not save it, which allows it to be shown interactively or modified further before saving.

  • cells_to_plot_column: SingleCellColumn | None

    an optional Boolean column of obs indicating which cells to plot. Can be a column name, a polars expression, a polars Series, a 1D NumPy array, or a function that takes in this SingleCell dataset and returns a polars Series or 1D NumPy array. Set to None to plot all cells passing QC.

  • ax: 'Axes' | None

    the Matplotlib axes to save the plot onto; if None, create a new figure with Matpotlib’s constrained layout and plot onto it

  • figure_kwargs: dict[str, Any] | None

    a dictionary of keyword arguments to be passed to plt.figure() when ax is None, such as:

    • figsize: a two-element sequence of the width and height of the figure in inches. Defaults to [8, 6], 25% larger than Matplotlib’s default of [6.4, 4.8].

    • layout: the layout mechanism used by Matplotlib to avoid overlapping plot elements. Defaults to ‘constrained’, instead of Matplotlib’s default of None.

  • point_size: int | float | str | None

    the size of the points for each cell; defaults to 20,000 divided by the number of cells. Can be a single number, or the name of a column of obs to make each point a different size.

  • sort_by_frequency: bool

    if True, assign colors and sort the legend in order of decreasing frequency; if False (the default), use natural sort order. Cannot be True unless colormap is None and color_column is discrete; if colormap is not None, the plot order is determined by the order of the keys in colormap.

  • colormap: str | 'Colormap' | dict[Any, Color]

    a string or Colormap object indicating the Matplotlib colormap to use; or, if color_column is discrete, a dictionary mapping values in color_column to Matplotlib colors (cells with values of color_column that are not in the dictionary will be plotted in the color default_color). Defaults to plt.rcParams[‘image.cmap’] (‘viridis’ by default) if color_column is continous, or the colors from a maximally perceptually distinct colormap if color_column is discrete (with colors assigned in decreasing order of frequency). Cannot be specified if color_column is None.

  • lightness_range: tuple[float, float] | None

    a two-element tuple with the lightness range of colors to generate, or None to take the full range: [0, 100]. Can only be specified when color_column is discrete and colormap is None.

  • chroma_range: tuple[float, float] | None

    a two-element tuple with the chroma range of colors to generate, or None to take the full range: [0, 100]. Grays have low chroma, and vivid colors have high chroma. Can only be specified when color_column is discrete and colormap is None.

  • hue_range: tuple[float, float] | None

    a two-element tuple with the hue range of colors to generate, or None to take the full range: [0, 360]. Red is at 0°, green at 120°, and blue at 240°. Because it wraps around, the first element of the tuple can be greater than the second, unlike for lightness_range and chroma_range. Can only be specified when color_column is discrete and colormap is None.

  • first_color: Color

    the first color of the palette. Can be any valid Matplotlib color, like a hex string (e.g. ‘#FF0000’), a named color (e.g. ‘red’), a 3- or 4-element RGB/RGBA tuple of integers 0-255 or floats 0-1, or a single float 0-1 for grayscale.

  • stride: int

    as an optimization, consider only RGB colors where R, G, and B are all multiples of this value. Must be a small divisor of 255: 1, 3, 5, 15, or 17. Set to 1 for the best possible solution, at orders of magnitude more computational cost.

  • default_color: Color

    the default color to plot cells in when color_column is None, or when certain cells have missing (null) values for color_column, or when colormap is a dictionary and some cells have values of color_column that are not in the dictionary. Can be any valid Matplotlib color, like a hex string (e.g. ‘#FF0000’), a named color (e.g. ‘red’), a 3- or 4-element RGB/RGBA tuple of integers 0-255 or floats 0-1, or a single float 0-1 for grayscale.

  • scatter_kwargs: dict[str, Any] | None

    a dictionary of keyword arguments to be passed to ax.scatter(), such as:

    • rasterized: whether to convert the scatter plot points to a raster (bitmap) image when saving to a vector format like PDF. Defaults to True, instead of Matplotlib’s default of False.

    • marker: the shape to use for plotting each cell

    • norm, vmin, and vmax: control how the colormap maps the numbers in color_column to colors, if color_column is numeric

    • alpha: the transparency of each point

    • linewidths and edgecolors: the width and color of the borders around each marker. These are absent by default (linewidths=0, edgecolors=(0, 0, 0, 0)), unlike Matplotlib’s default. Both arguments can be either single values or sequences.

    • zorder: the order in which the cells are plotted, with higher values appearing on top of lower ones.

    Specifying s, c/color, or cmap will raise an error, since these arguments conflict with the point_size, color_column, and colormap arguments, respectively.

  • label: bool

    whether to label cells with each distinct value of color_column. Labels will be placed at the median x and y position of the points with that color. Can only be True when color_column is discrete. When set to True, you may also want to set legend=False to avoid redundancy.

  • label_kwargs: dict[str, Any] | None

    a dictionary of keyword arguments to be passed to ax.text() when adding labels to control the text properties, such as:

    • color and size to modify the text color/size

    • verticalalignment and horizontalalignment to control vertical and horizontal alignment. By default, unlike Matplotlib, these are both set to ‘center’.

    • path_effects to set properties for the border around the text. By default, set to matplotlib.patheffects.withStroke(linewidth=3, foreground=’white’, alpha=0.75) instead of Matplotlib’s default of None, to put a semi-transparent white border around the labels for better contrast.

    Can only be specified when label=True.

  • legend: bool

    whether to add a legend for each value in color_column. Ignored unless color_column is discrete.

  • legend_kwargs: dict[str, Any] | None

    a dictionary of keyword arguments to be passed to ax.legend() to modify the legend, such as:

    • loc, bbox_to_anchor, and bbox_transform to set its location. By default, loc is set to ‘center left’ and bbox_to_anchor to (1, 0.5) to put the legend to the right of the plot, anchored at the middle.

    • ncols to set its number of columns. By default, set to ceil(obs[color_column].n_unique() / 24) to have at most 24 items per column.

    • prop, fontsize, and labelcolor to set its font properties

    • facecolor and framealpha to set its background color and transparency

    • frameon=True or edgecolor to add or color its border. frameon defaults to False, instead of Matplotlib’s default of True.

    • title to add a legend title

    Can only be specified when color_column is discrete and legend=True.

  • colorbar: bool

    whether to add a colorbar. Ignored unless color_column is quantitative.

  • colorbar_kwargs: dict[str, Any] | None

    a dictionary of keyword arguments to be passed to plt.colorbar(), such as:

    • location: ‘left’, ‘right’, ‘top’, or ‘bottom’

    • orientation: ‘vertical’ or ‘horizontal’

    • fraction: the fraction of the axes to allocate to the colorbar. Defaults to 0.15.

    • shrink: the fraction to multiply the size of the colorbar by. Defaults to 0.5, instead of Matplotlib’s default of 1.

    • aspect: the ratio of the colorbar’s long to short dimensions. Defaults to 20.

    • pad: the fraction of the axes between the colorbar and the rest of the figure. Defaults to 0.01, instead of Matplotlib’s default of 0.05 if vertical and 0.15 if horizontal.

    Can only be specified when color_column is quantitative and colorbar=True.

  • title: str | None

    the title of the plot, or None to not add a title

  • title_kwargs: dict[str, Any] | None

    a dictionary of keyword arguments to be passed to ax.set_title() to control text properties, such as color and size. Can only be specified when title is not None.

  • xlabel: str | None

    the x-axis label, or None to not label the x-axis

  • xlabel_kwargs: dict[str, Any] | None

    a dictionary of keyword arguments to be passed to ax.set_xlabel() to control text properties, such as color and size. Can only be specified when xlabel is not None.

  • ylabel: str | None

    the y-axis label, or None to not label the y-axis

  • ylabel_kwargs: dict[str, Any] | None

    a dictionary of keyword arguments to be passed to ax.set_ylabel() to control text properties, such as color and size. Can only be specified when ylabel is not None.

  • xlim: tuple[int | float, int | float] | None

    a length-2 tuple of the left and right x-axis limits, or None to set the limits based on the data

  • ylim: tuple[int | float, int | float] | None

    a length-2 tuple of the bottom and top y-axis limits, or None to set the limits based on the data

  • despine: bool

    whether to remove the top and right spines (borders of the plot area) from the plot

  • savefig_kwargs: dict[str, Any] | None

    a dictionary of keyword arguments to be passed to plt.savefig(), such as:

    • dpi: defaults to 300 instead of Matplotlib’s default of 150

    • bbox_inches: the bounding box of the portion of the figure to save; defaults to ‘tight’ (crop out any blank borders) instead of Matplotlib’s default of None (save the entire figure)

    • pad_inches: the number of inches of padding to add on each of the four sides of the figure when saving. Defaults to ‘layout’ (use the padding from the constrained layout engine, when ax is not None) instead of Matplotlib’s default of 0.1.

    • transparent: whether to save with a transparent background; defaults to True if saving to a PDF (i.e. when filename ends with ‘.pdf’) and False otherwise, instead of Matplotlib’s default of always being False.

    Can only be specified when filename is specified.

Return type:

None