qdiv.plot.ordination_plots module
- class qdiv.plot.ordination_plots.Patch(*, edgecolor=None, facecolor=None, color=None, linewidth=None, linestyle=None, antialiased=None, hatch=None, fill=True, capstyle=None, joinstyle=None, **kwargs)[source]
Bases:
ArtistA patch is a 2D artist with a face color and an edge color.
If any of edgecolor, facecolor, linewidth, or antialiased are None, they default to their rc params setting.
The following kwarg properties are supported
- Properties:
agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: unknown animated: bool antialiased or aa: bool or None capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color: :mpltype:`color` edgecolor or ec: :mpltype:`color` or None facecolor or fc: :mpltype:`color` or None figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fill: bool gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle or ls: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth or lw: float or None mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str visible: bool zorder: float
- get_verts()[source]
Return a copy of the vertices used in this patch.
If the patch contains Bézier curves, the curves will be interpolated by line segments. To access the curves as curves, use get_path.
- contains(mouseevent, radius=None)[source]
Test whether the mouse event occurred in the patch.
- Parameters:
mouseevent (~matplotlib.backend_bases.MouseEvent) – Where the user clicked.
radius (float, optional) –
Additional margin on the patch in target coordinates of .Patch.get_transform. See .Path.contains_point for further details.
If None, the default value depends on the state of the object:
If .Artist.get_picker is a number, the default is that value. This is so that picking works as expected.
Otherwise if the edge color has a non-zero alpha, the default is half of the linewidth. This is so that all the colored pixels are “in” the patch.
Finally, if the edge has 0 alpha, the default is 0. This is so that patches without a stroked edge do not have points outside of the filled region report as “in” due to an invisible edge.
- Return type:
(bool, empty dict)
- contains_point(point, radius=None)[source]
Return whether the given point is inside the patch.
- Parameters:
point ((float, float)) – The point (x, y) to check, in target coordinates of
.Patch.get_transform(). These are display coordinates for patches that are added to a figure or Axes.radius (float, optional) –
Additional margin on the patch in target coordinates of .Patch.get_transform. See .Path.contains_point for further details.
If None, the default value depends on the state of the object:
If .Artist.get_picker is a number, the default is that value. This is so that picking works as expected.
Otherwise if the edge color has a non-zero alpha, the default is half of the linewidth. This is so that all the colored pixels are “in” the patch.
Finally, if the edge has 0 alpha, the default is 0. This is so that patches without a stroked edge do not have points outside of the filled region report as “in” due to an invisible edge.
- Return type:
bool
Notes
The proper use of this method depends on the transform of the patch. Isolated patches do not have a transform. In this case, the patch creation coordinates and the point coordinates match. The following example checks that the center of a circle is within the circle
>>> center = 0, 0 >>> c = Circle(center, radius=1) >>> c.contains_point(center) True
The convention of checking against the transformed patch stems from the fact that this method is predominantly used to check if display coordinates (e.g. from mouse events) are within the patch. If you want to do the above check with data coordinates, you have to properly transform them first:
>>> center = 0, 0 >>> c = Circle(center, radius=3) >>> plt.gca().add_patch(c) >>> transformed_interior_point = c.get_data_transform().transform((0, 2)) >>> c.contains_point(transformed_interior_point) True
- contains_points(points, radius=None)[source]
Return whether the given points are inside the patch.
- Parameters:
points ((N, 2) array) – The points to check, in target coordinates of
self.get_transform(). These are display coordinates for patches that are added to a figure or Axes. Columns contain x and y values.radius (float, optional) –
Additional margin on the patch in target coordinates of .Patch.get_transform. See .Path.contains_point for further details.
If None, the default value depends on the state of the object:
If .Artist.get_picker is a number, the default is that value. This is so that picking works as expected.
Otherwise if the edge color has a non-zero alpha, the default is half of the linewidth. This is so that all the colored pixels are “in” the patch.
Finally, if the edge has 0 alpha, the default is 0. This is so that patches without a stroked edge do not have points outside of the filled region report as “in” due to an invisible edge.
- Return type:
length-N bool array
Notes
The proper use of this method depends on the transform of the patch. See the notes on .Patch.contains_point.
- get_data_transform()[source]
Return the ~.transforms.Transform mapping data coordinates to physical coordinates.
- get_patch_transform()[source]
Return the ~.transforms.Transform instance mapping patch coordinates to data coordinates.
For example, one may define a patch of a circle which represents a radius of 5 by providing coordinates for a unit circle, and a transform which scales the coordinates (the patch coordinate) by 5.
- set_antialiased(aa)[source]
Set whether to use antialiased rendering.
- Parameters:
aa (bool or None)
- set_edgecolor(color)[source]
Set the patch edge color.
- Parameters:
color (:mpltype:`color` or None)
- set_facecolor(color)[source]
Set the patch face color.
- Parameters:
color (:mpltype:`color` or None)
- set_color(c)[source]
Set both the edgecolor and the facecolor.
- Parameters:
c (:mpltype:`color`)
See also
- set_alpha(alpha)[source]
Set the alpha value used for blending - not supported on all backends.
- Parameters:
alpha (float or None) – alpha must be within the 0-1 range, inclusive.
- set_linestyle(ls)[source]
Set the patch linestyle.
linestyle
description
'-'or'solid'solid line
'--'or'dashed'dashed line
'-.'or'dashdot'dash-dotted line
':'or'dotted'dotted line
'none','None',' ', or''draw nothing
Alternatively a dash tuple of the following form can be provided:
(offset, onoffseq)
where
onoffseqis an even length tuple of on and off ink in points.- Parameters:
ls ({'-', '--', '-.', ':', '', (offset, on-off-seq), ...}) – The line style.
- property fill
Return whether the patch is filled.
- set_capstyle(s)[source]
Set the .CapStyle.
The default capstyle is ‘round’ for .FancyArrowPatch and ‘butt’ for all other patches.
- Parameters:
s (.CapStyle or {‘butt’, ‘projecting’, ‘round’})
- set_joinstyle(s)[source]
Set the .JoinStyle.
The default joinstyle is ‘round’ for .FancyArrowPatch and ‘miter’ for all other patches.
- Parameters:
s (.JoinStyle or {‘miter’, ‘round’, ‘bevel’})
- set_hatch(hatch)[source]
Set the hatching pattern.
hatch can be one of:
/ - diagonal hatching \ - back diagonal | - vertical - - horizontal + - crossed x - crossed diagonal o - small circle O - large circle . - dots * - stars
Letters can be combined, in which case all the specified hatchings are done. If same letter repeats, it increases the density of hatching of that pattern.
- Parameters:
hatch ({'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'})
- draw(renderer)[source]
Draw the Artist (and its children) using the given renderer.
This has no effect if the artist is not visible (.Artist.get_visible returns False).
- Parameters:
renderer (~matplotlib.backend_bases.RendererBase subclass.)
Notes
This method is overridden in the Artist subclasses.
- get_window_extent(renderer=None)[source]
Get the artist’s bounding box in display space.
The bounding box’ width and height are nonnegative.
Subclasses should override for inclusion in the bounding box “tight” calculation. Default is to return an empty bounding box at 0, 0.
Be careful when using this function, the results will not update if the artist window extent of the artist changes. The extent can change due to any changes in the transform stack, such as changing the Axes limits, the figure size, or the canvas used (as is done when saving a figure). This can lead to unexpected behavior where interactive figures will look fine on the screen, but will save incorrectly.
- get_aa()
Alias for get_antialiased.
- get_ec()
Alias for get_edgecolor.
- get_fc()
Alias for get_facecolor.
- get_ls()
Alias for get_linestyle.
- get_lw()
Alias for get_linewidth.
- set(*, agg_filter=<UNSET>, alpha=<UNSET>, animated=<UNSET>, antialiased=<UNSET>, capstyle=<UNSET>, clip_box=<UNSET>, clip_on=<UNSET>, clip_path=<UNSET>, color=<UNSET>, edgecolor=<UNSET>, facecolor=<UNSET>, fill=<UNSET>, gid=<UNSET>, hatch=<UNSET>, hatch_linewidth=<UNSET>, in_layout=<UNSET>, joinstyle=<UNSET>, label=<UNSET>, linestyle=<UNSET>, linewidth=<UNSET>, mouseover=<UNSET>, path_effects=<UNSET>, picker=<UNSET>, rasterized=<UNSET>, sketch_params=<UNSET>, snap=<UNSET>, transform=<UNSET>, url=<UNSET>, visible=<UNSET>, zorder=<UNSET>)
Set multiple properties at once.
Supported properties are
- Properties:
agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array and two offsets from the bottom left corner of the image alpha: unknown animated: bool antialiased: bool or None capstyle: .CapStyle or {‘butt’, ‘projecting’, ‘round’} clip_box: ~matplotlib.transforms.BboxBase or None clip_on: bool clip_path: Patch or (Path, Transform) or None color: :mpltype:`color` edgecolor: :mpltype:`color` or None facecolor: :mpltype:`color` or None figure: ~matplotlib.figure.Figure or ~matplotlib.figure.SubFigure fill: bool gid: str hatch: {‘/’, ‘\’, ‘|’, ‘-’, ‘+’, ‘x’, ‘o’, ‘O’, ‘.’, ‘*’} hatch_linewidth: unknown in_layout: bool joinstyle: .JoinStyle or {‘miter’, ‘round’, ‘bevel’} label: object linestyle: {‘-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …} linewidth: float or None mouseover: bool path_effects: list of .AbstractPathEffect picker: None or bool or float or callable rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform: ~matplotlib.transforms.Transform url: str visible: bool zorder: float
- set_aa(aa)
Alias for set_antialiased.
- set_ec(color)
Alias for set_edgecolor.
- set_fc(color)
Alias for set_facecolor.
- set_ls(ls)
Alias for set_linestyle.
- set_lw(w)
Alias for set_linewidth.
- class qdiv.plot.ordination_plots.TextPath(xy, s, size=None, prop=None, _interpolation_steps=1, usetex=False)[source]
Bases:
PathCreate a path from the text.
Create a path from the text. Note that it simply is a path, not an artist. You need to use the .PathPatch (or other artists) to draw this path onto the canvas.
- Parameters:
xy (tuple or array of two float values) – Position of the text. For no offset, use
xy=(0, 0).s (str) – The text to convert to a path.
size (float, optional) – Font size in points. Defaults to the size specified via the font properties prop.
prop (~matplotlib.font_manager.FontProperties, optional) – Font property. If not provided, will use a default .FontProperties with parameters from the rcParams.
_interpolation_steps (int, optional) – (Currently ignored)
usetex (bool, default: False) – Whether to use tex rendering.
Examples
The following creates a path from the string “ABC” with Helvetica font face; and another path from the latex fraction 1/2:
from matplotlib.text import TextPath from matplotlib.font_manager import FontProperties fp = FontProperties(family="Helvetica", style="italic") path1 = TextPath((12, 12), "ABC", size=12, prop=fp) path2 = TextPath((0, 0), r"$\frac{1}{2}$", size=12, usetex=True)
Also see /gallery/text_labels_and_annotations/demo_text_path.
- property vertices
Return the cached path after updating it if necessary.
- property codes
Return the codes
- class qdiv.plot.ordination_plots.FontProperties(family=None, style=None, variant=None, weight=None, stretch=None, size=None, fname=None, math_fontfamily=None)[source]
Bases:
objectA class for storing and manipulating font properties.
The font properties are the six properties described in the W3C Cascading Style Sheet, Level 1 font specification and math_fontfamily for math fonts:
family: A list of font names in decreasing order of priority. The items may include a generic font family name, either ‘sans-serif’, ‘serif’, ‘cursive’, ‘fantasy’, or ‘monospace’. In that case, the actual font to be used will be looked up from the associated rcParam during the search process in .findfont. Default: :rc:`font.family`
style: Either ‘normal’, ‘italic’ or ‘oblique’. Default: :rc:`font.style`
variant: Either ‘normal’ or ‘small-caps’. Default: :rc:`font.variant`
stretch: A numeric value in the range 0-1000 or one of ‘ultra-condensed’, ‘extra-condensed’, ‘condensed’, ‘semi-condensed’, ‘normal’, ‘semi-expanded’, ‘expanded’, ‘extra-expanded’ or ‘ultra-expanded’. Default: :rc:`font.stretch`
weight: A numeric value in the range 0-1000 or one of ‘ultralight’, ‘light’, ‘normal’, ‘regular’, ‘book’, ‘medium’, ‘roman’, ‘semibold’, ‘demibold’, ‘demi’, ‘bold’, ‘heavy’, ‘extra bold’, ‘black’. Default: :rc:`font.weight`
size: Either a relative value of ‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’ or an absolute font size, e.g., 10. Default: :rc:`font.size`
math_fontfamily: The family of fonts used to render math text. Supported values are: ‘dejavusans’, ‘dejavuserif’, ‘cm’, ‘stix’, ‘stixsans’ and ‘custom’. Default: :rc:`mathtext.fontset`
Alternatively, a font may be specified using the absolute path to a font file, by using the fname kwarg. However, in this case, it is typically simpler to just pass the path (as a pathlib.Path, not a str) to the font kwarg of the .Text object.
The preferred usage of font sizes is to use the relative values, e.g., ‘large’, instead of absolute font sizes, e.g., 12. This approach allows all text sizes to be made larger or smaller based on the font manager’s default font size.
This class accepts a single positional string as fontconfig pattern, or alternatively individual properties as keyword arguments:
FontProperties(pattern) FontProperties(*, family=None, style=None, variant=None, ...)
This support does not depend on fontconfig; we are merely borrowing its pattern syntax for use here.
Note that Matplotlib’s internal font manager and fontconfig use a different algorithm to lookup fonts, so the results of the same pattern may be different in Matplotlib than in other applications that use fontconfig.
- get_family()[source]
Return a list of individual font family names or generic family names.
The font families or generic font families (which will be resolved from their respective rcParams when searching for a matching font) in the order of preference.
- get_weight()[source]
Get the font weight. Options are: A numeric value in the range 0-1000 or one of ‘light’, ‘normal’, ‘regular’, ‘book’, ‘medium’, ‘roman’, ‘semibold’, ‘demibold’, ‘demi’, ‘bold’, ‘heavy’, ‘extra bold’, ‘black’
- get_stretch()[source]
Return the font stretch or width. Options are: ‘ultra-condensed’, ‘extra-condensed’, ‘condensed’, ‘semi-condensed’, ‘normal’, ‘semi-expanded’, ‘expanded’, ‘extra-expanded’, ‘ultra-expanded’.
- get_fontconfig_pattern()[source]
Get a fontconfig pattern suitable for looking up the font as specified with fontconfig’s
fc-matchutility.This support does not depend on fontconfig; we are merely borrowing its pattern syntax for use here.
- set_family(family)[source]
Change the font family. Can be either an alias (generic name is CSS parlance), such as: ‘serif’, ‘sans-serif’, ‘cursive’, ‘fantasy’, or ‘monospace’, a real font name or a list of real font names. Real font names are not supported when :rc:`text.usetex` is True. Default: :rc:`font.family`
- set_style(style)[source]
Set the font style.
- Parameters:
style ({‘normal’, ‘italic’, ‘oblique’}, default: :rc:`font.style`)
- set_variant(variant)[source]
Set the font variant.
- Parameters:
variant ({‘normal’, ‘small-caps’}, default: :rc:`font.variant`)
- set_weight(weight)[source]
Set the font weight.
- Parameters:
weight (int or {‘ultralight’, ‘light’, ‘normal’, ‘regular’, ‘book’, ‘medium’, ‘roman’, ‘semibold’, ‘demibold’, ‘demi’, ‘bold’, ‘heavy’, ‘extra bold’, ‘black’}, default: :rc:`font.weight`) – If int, must be in the range 0-1000.
- set_stretch(stretch)[source]
Set the font stretch or width.
- Parameters:
stretch (int or {‘ultra-condensed’, ‘extra-condensed’, ‘condensed’, ‘semi-condensed’, ‘normal’, ‘semi-expanded’, ‘expanded’, ‘extra-expanded’, ‘ultra-expanded’}, default: :rc:`font.stretch`) – If int, must be in the range 0-1000.
- set_size(size)[source]
Set the font size.
- Parameters:
size (float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}, default: :rc:`font.size`) – If a float, the font size in points. The string values denote sizes relative to the default font size.
- set_file(file)[source]
Set the filename of the fontfile to use. In this case, all other properties will be ignored.
- set_fontconfig_pattern(pattern)[source]
Set the properties by parsing a fontconfig pattern.
This support does not depend on fontconfig; we are merely borrowing its pattern syntax for use here.
- get_math_fontfamily()[source]
Return the name of the font family used for math text.
The default font is :rc:`mathtext.fontset`.
- set_math_fontfamily(fontfamily)[source]
Set the font family for text in math mode.
If not set explicitly, :rc:`mathtext.fontset` will be used.
- Parameters:
fontfamily (str) –
The name of the font family.
Available font families are defined in the default matplotlibrc file.
See also
text.Text.get_math_fontfamily
- set_name(family)
Change the font family. Can be either an alias (generic name is CSS parlance), such as: ‘serif’, ‘sans-serif’, ‘cursive’, ‘fantasy’, or ‘monospace’, a real font name or a list of real font names. Real font names are not supported when :rc:`text.usetex` is True. Default: :rc:`font.family`
- get_slant()
Return the font style. Values are: ‘normal’, ‘italic’ or ‘oblique’.
- set_slant(style)
Set the font style.
- Parameters:
style ({‘normal’, ‘italic’, ‘oblique’}, default: :rc:`font.style`)
- get_size_in_points()
Return the font size.
- qdiv.plot.ordination_plots.ordination(ordination_results=None, meta=None, *, color_by=None, shape_by=None, order=None, biplot=None, ellipse=None, title='', savename=None, show_legend=True, figsize=(9, 6), fontsize=12, markersize=50, markerscale=1.1, lw=1.0, pad=1.1, flipx=False, flipy=False, hide_ticks=False, connect=None, ellipse_connect=None, ellipse_std=2.0, tag=None, return_data=False, colors=None, markers=None, ellipse_colors=None, color_legend_marker=None, color_legend_title=None, shape_legend_title=None, which_axes=(0, 1), ax=None, legend_pos_colors=(1.0, 1.0), legend_pos_shapes=(1.0, 0.4))[source]
Create an ordination plot (PCoA or db-RDA) with optional grouping, biplots, and annotations.
- Parameters:
ordination_results (pandas.DataFrame or dict) –
If a dissimilarity matrix (square DataFrame) is provided, stats.pcoa_lingoes will be run and a PCoA plotted.
If a results dict from stats.pcoa_lingoes or stats.dbrda is provided, those results will be plotted directly.
meta (DataFrame | MicrobiomeData-like | dict) – Metadata table with sample annotations.
color_by (str, optional) – Column in meta used to color points by group.
shape_by (str, optional) – Column in meta used to vary marker shapes by group.
order (str, optional) – Metadata column used to order samples for the color_by variable.
biplot (list of str, optional) – For PCoA: list of numeric metadata columns to display as biplot vectors. For db-RDA: set to None to use ‘biplot_scores’ from ordination results.
ellipse (str, optional) – Column in meta used to group samples for drawing confidence ellipses.
title (str, optional) – Plot title.
savename (str, optional) – Filename to save the figure. Extension determines format (e.g., .png, .pdf).
show_legend (bool, default=True) – Whether to display the legend.
figsize (tuple of float, default=(9, 6)) – Figure size in inches.
fontsize (int, default=12) – Font size for labels and title.
markersize (float, default=50) – Size of scatter plot markers.
markerscale (float, default=1.1) – Scaling factor for legend markers.
lw (float, default=1.0) – Line width for ellipses and connections.
pad (float, default=1.1) – Padding factor for axis limits.
flipx (bool, default=False) – Flip the X-axis.
flipy (bool, default=False) – Flip the Y-axis.
hide_ticks (bool, default=False) – Hide axis ticks and labels.
connect (str, optional) – Column in meta to connect points in order (e.g., time series).
ellipse_connect (str, optional) – Column in meta to connect ellipse centers in order.
ellipse_std (float, default=2.0) – Number of standard deviations around the centroid that the ellipse is drawn.
tag (str, optional) – Column in meta or ‘index’ to annotate points.
return_data (bool, default=False) – If True, return processed plotting data instead of the figure.
colors (list of str, optional) – Custom list of colors for groups.
markers (list of str, optional) – Custom list of marker styles for groups.
ellipse_colors (list of str, optional) – Custom list of colors for ellipses.
color_legend_marker (str, default=None) – Shape of color legend marker. Defaults to a rectangular patch.
color_legend_title (str, optional) – Color legend title.
shape_legend_title (str, optional) – Marker legend title.
which_axes (tuple of int, default=(0, 1)) – Indices of ordination axes to plot.
ax (matplotlib.axes.Axes, optional) – Existing axes to draw the plot on. If None, a new figure is created.
legend_pos_colors (tuple of float, default=(1, 1)) – Position of color legend. Only relevant for user-supplied ax.
legend_pos_shapes (tuple of float, default=(1, 0.4)) – Position of shape legend. Only relevant for user-supplied ax.
- Returns:
fig (matplotlib.figure.Figure) – The matplotlib Figure object for the ordination.
ax (matplotlib.axes.Axes) – The matplotlib Axes object for the ordination.
meta (pandas.DataFrame) – meta data with ordination coordinates.
Uproj (pandas.DataFrame) – biplot coordinates (if used)
- Return type:
Tuple[Figure, axes, DataFrame, DataFrame]
Notes
Supports both PCoA and db-RDA ordination results.
Ellipses represent group dispersion; biplots show variable contributions.
Axis flipping and padding allow fine control over plot appearance.
Examples
>>> fig = ordination(pcoa_results, meta, color_by='Treatment', ellipse='Group') >>> fig.savefig('ordination_plot.png')