Module bioiain.visualisation.plots
Functions
def fig2D(**kwargs)-
Expand source code
def fig2D(**kwargs): fig = plt.figure(**kwargs) ax = fig.add_subplot(111) ax.set_aspect('equal') return fig, ax def fig3D(entity:= None,
preset: str = None,
fig: matplotlib.figure.Figure = None,
ax: matplotlib.axes._axes.Axes = None) ‑> list[matplotlib.figure.Figure | matplotlib.axes._axes.Axes]-
Expand source code
def fig3D(entity:any=None, preset:str=None, fig:mpl.pyplot.Figure=None, ax:mpl.pyplot.Axes=None) -> list[mpl.pyplot.Figure|mpl.pyplot.Axes]: """ Initialises a 3-Dimensional Matplotlib plot, optionally using a preset. :param entity: (Optional) The entity to plot, might be required in some presets. :param preset: Name of preset to use. :param fig: Use this figure instead of new one. :param ax: Use these axes instead of new ones. :return: Figures and Axes generated. """ if fig is None: fig = plt.figure() if ax is None: ax = fig.add_subplot(111, projection='3d') ax.set_aspect('equal') if preset == "crystal-frac": ax.set_xticks([-1, 0, 1, 2]) ax.set_yticks([-1, 0, 1, 2]) ax.set_zticks([-1, 0, 1, 2]) ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z") ax.axes.set_xlim(-1,2) ax.axes.set_ylim(-1,2) ax.axes.set_zlim(-1,2) else: log("warning", "3D Plot preset ({}) not found".format(preset)) return [fig, ax]Initialises a 3-Dimensional Matplotlib plot, optionally using a preset. :param entity: (Optional) The entity to plot, might be required in some presets. :param preset: Name of preset to use. :param fig: Use this figure instead of new one. :param ax: Use these axes instead of new ones. :return: Figures and Axes generated.
def grid2D(rows, columns, height=5, width=5, as_grid=False)-
Expand source code
def grid2D(rows, columns, height=5, width=5, as_grid=False): log(2, f"Creating {rows}x{columns} (rxc) grid...") fig, grid_axes = plt.subplots(rows, columns, figsize=(columns*width, rows*height)) if as_grid: return fig, grid_axes axes = [] for row in grid_axes: axes.extend(row) return fig, axes def plot_confusion(preds, labels, title, score=None, classes=None)-
Expand source code
def plot_confusion(preds, labels, title, score=None, classes=None): try: log(1, "Plotting confusion...") cm = confusion_matrix(labels, preds) if classes is None: classes = list(set(labels)) plt.figure(figsize=(1*len(classes) ,1*len(classes))) sb.heatmap(cm, annot=True, fmt="d", cmap="Blues", xticklabels=classes, yticklabels=classes) plt.xlabel("Predicted") plt.ylabel("True") if score is not None: title = f"{title}_S={score:.2f}" plt.title(title) os.makedirs("figs", exist_ok=True) path = f"figs/{title}.confusion.png" plt.savefig(path) plt.close() return cm, path except Exception as e: print(e) def plot_heatmap(matrix, show=False, filename=None)-
Expand source code
def plot_heatmap(matrix, show=False, filename=None): fig = plt.figure() ax = fig.add_subplot() ax.imshow(matrix) if filename is not None: plt.savefig(filename) if show: plt.show(block=True)
Classes
class Arrow3D (xs, ys, zs, *args, **kwargs)-
Expand source code
class Arrow3D(FancyArrowPatch): def __init__(self, xs, ys, zs, *args, **kwargs): arrow_prop_dict = dict(mutation_scale=20, arrowstyle='-|>', color='k', shrinkA=0, shrinkB=0) kwargs = arrow_prop_dict | kwargs super().__init__((0,0), (0,0), *args, **kwargs) self._verts3d = xs, ys, zs def do_3d_projection(self, renderer=None): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, self.axes.M) self.set_positions((xs[0],ys[0]),(xs[1],ys[1])) return np.min(zs)A fancy arrow patch.
It draws an arrow using the
ArrowStyle. It is primarily used by the~.axes.Axes.annotatemethod. For most purposes, use the annotate method for drawing arrows.The head and tail positions are fixed at the specified start and end points of the arrow, but the size and shape (in display coordinates) of the arrow does not change when the axis is moved or zoomed.
Defining the arrow position and path
There are two ways to define the arrow position and path:
- Start, end and connection: The typical approach is to define the start and end points of the arrow using posA and posB. The curve between these two can further be configured using connectionstyle.
If given, the arrow curve is clipped by patchA and patchB, allowing it to start/end at the border of these patches. Additionally, the arrow curve can be shortened by shrinkA and shrinkB to create a margin between start/end (after possible clipping) and the drawn arrow.
- path: Alternatively if path is provided, an arrow is drawn along this Path. In this case, connectionstyle, patchA, patchB, shrinkA, and shrinkB are ignored.
Styling
The arrowstyle defines the styling of the arrow head, tail and shaft. The resulting arrows can be styled further by setting the
.Patchproperties such as linewidth, color, facecolor, edgecolor etc. via keyword arguments.Parameters
posA,posB:(float, float), optional-
(x, y) coordinates of start and end point of the arrow. The actually drawn start and end positions may be modified through patchA, patchB, shrinkA, and shrinkB.
posA, posB are exclusive of path.
path:~matplotlib.path.Path, optional-
If provided, an arrow is drawn along this path and patchA, patchB, shrinkA, and shrinkB are ignored.
path is exclusive of posA, posB.
arrowstyle:stror.ArrowStyle, default: 'simple'-
The styling of arrow head, tail and shaft. This can be
.ArrowStyleor one of its subclasses- The shorthand string name (e.g. "->") as given in the table below, optionally containing a comma-separated list of style parameters, e.g. "->, head_length=10, head_width=5".
The style parameters are scaled by mutation_scale.
The following arrow styles are available. See also :doc:
/gallery/text_labels_and_annotations/fancyarrow_demo.============= ========== =============================================================================================================================== Class Name Parameters
============= ========== =============================================================================================================================== Curve-None
CurveA<-head_length=0.4, head_width=0.2, widthA=1.0, widthB=1.0, lengthA=0.2, lengthB=0.2, angleA=0, angleB=0, scaleA=None, scaleB=None CurveB->head_length=0.4, head_width=0.2, widthA=1.0, widthB=1.0, lengthA=0.2, lengthB=0.2, angleA=0, angleB=0, scaleA=None, scaleB=None CurveAB<->head_length=0.4, head_width=0.2, widthA=1.0, widthB=1.0, lengthA=0.2, lengthB=0.2, angleA=0, angleB=0, scaleA=None, scaleB=None CurveFilledA<|-head_length=0.4, head_width=0.2, widthA=1.0, widthB=1.0, lengthA=0.2, lengthB=0.2, angleA=0, angleB=0, scaleA=None, scaleB=None CurveFilledB-|>head_length=0.4, head_width=0.2, widthA=1.0, widthB=1.0, lengthA=0.2, lengthB=0.2, angleA=0, angleB=0, scaleA=None, scaleB=None CurveFilledAB<|-|>head_length=0.4, head_width=0.2, widthA=1.0, widthB=1.0, lengthA=0.2, lengthB=0.2, angleA=0, angleB=0, scaleA=None, scaleB=None BracketA]-widthA=1.0, lengthA=0.2, angleA=0
BracketB-[widthB=1.0, lengthB=0.2, angleB=0
BracketAB]-[widthA=1.0, lengthA=0.2, angleA=0, widthB=1.0, lengthB=0.2, angleB=0
BarAB|-|widthA=1.0, angleA=0, widthB=1.0, angleB=0
BracketCurve]->widthA=1.0, lengthA=0.2, angleA=None
CurveBracket<-[widthB=1.0, lengthB=0.2, angleB=None
Simplesimplehead_length=0.5, head_width=0.5, tail_width=0.2
Fancyfancyhead_length=0.4, head_width=0.4, tail_width=0.4
Wedgewedgetail_width=0.3, shrink_factor=0.5
============= ========== ===============================================================================================================================Only the styles
<|-,-|>,<|-|>simple,fancyandwedgecontain closed paths and can be filled. connectionstyle:stror.ConnectionStyleorNone, optional, default: 'arc3'-
.ConnectionStylewith which posA and posB are connected. This can be.ConnectionStyleor one of its subclasses- The shorthand string name as given in the table below, e.g. "arc3".
====== ========== ================================================= Class Name Parameters
====== ========== ================================================= Arc3arc3rad=0.0
Angle3angle3angleA=90, angleB=0
AngleangleangleA=90, angleB=0, rad=0.0
ArcarcangleA=0, angleB=0, armA=None, armB=None, rad=0.0 BarbararmA=0.0, armB=0.0, fraction=0.3, angle=None
====== ========== =================================================Ignored if path is provided.
patchA,patchB:~matplotlib.patches.Patch, default: None-
Optional Patches at posA and posB, respectively. If given, the arrow path is clipped by these patches such that head and tail are at the border of the patches.
Ignored if path is provided.
shrinkA,shrinkB:float, default: 2-
Shorten the arrow path at posA and posB by this amount in points. This allows to add a margin between the intended start/end points and the arrow.
Ignored if path is provided.
mutation_scale:float, default: 1- Value with which attributes of arrowstyle (e.g., head_length) will be scaled.
mutation_aspect:Noneorfloat, default: None- The height of the rectangle will be squeezed by this value before the mutation and the mutated box will be stretched by the inverse of it.
Other Parameters
**kwargs:`~matplotlib.patches.Patchproperties`, optional- Here is a list of available
.Patchproperties:
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:
.CapStyleor {'butt', 'projecting', 'round'} clip_box:~matplotlib.transforms.BboxBaseor None clip_on: bool clip_path: Patch or (Path, Transform) or None color: :mpltype:coloredgecolor or ec: :mpltype:coloror None facecolor or fc: :mpltype:coloror None figure:~matplotlib.figure.Figureor~matplotlib.figure.SubFigurefill: bool gid: str hatch: {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'} hatch_linewidth: unknown in_layout: bool joinstyle:.JoinStyleor {'miter', 'round', 'bevel'} label: object linestyle or ls: {'-', '–', '-.', ':', '', (offset, on-off-seq), …} linewidth or lw: float or None mouseover: bool path_effects: list of.AbstractPathEffectpicker: None or bool or float or callable rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform:~matplotlib.transforms.Transformurl: str visible: bool zorder: floatIn contrast to other patches, the default
capstyleandjoinstyleforFancyArrowPatchare set to"round".Ancestors
- matplotlib.patches.FancyArrowPatch
- matplotlib.patches.Patch
- matplotlib.artist.Artist
Methods
def do_3d_projection(self, renderer=None)-
Expand source code
def do_3d_projection(self, renderer=None): xs3d, ys3d, zs3d = self._verts3d xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, self.axes.M) self.set_positions((xs[0],ys[0]),(xs[1],ys[1])) return np.min(zs) def set(self,
*,
agg_filter=<UNSET>,
alpha=<UNSET>,
animated=<UNSET>,
antialiased=<UNSET>,
arrowstyle=<UNSET>,
capstyle=<UNSET>,
clip_box=<UNSET>,
clip_on=<UNSET>,
clip_path=<UNSET>,
color=<UNSET>,
connectionstyle=<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>,
mutation_aspect=<UNSET>,
mutation_scale=<UNSET>,
patchA=<UNSET>,
patchB=<UNSET>,
path_effects=<UNSET>,
picker=<UNSET>,
positions=<UNSET>,
rasterized=<UNSET>,
sketch_params=<UNSET>,
snap=<UNSET>,
transform=<UNSET>,
url=<UNSET>,
visible=<UNSET>,
zorder=<UNSET>)-
Expand source code
cls.set = lambda self, **kwargs: Artist.set(self, **kwargs)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: float or None animated: bool antialiased or aa: bool or None arrowstyle: [ '-' | '<-' | '->' | '<->' | '<|-' | '-|>' | '<|-|>' | ']-' | '-[' | ']-[' | '|-|' | ']->' | '<-[' | 'simple' | 'fancy' | 'wedge' ] capstyle:
.CapStyleor {'butt', 'projecting', 'round'} clip_box:~matplotlib.transforms.BboxBaseor None clip_on: bool clip_path: Patch or (Path, Transform) or None color: :mpltype:colorconnectionstyle: [ 'arc3' | 'angle3' | 'angle' | 'arc' | 'bar' ] edgecolor or ec: :mpltype:coloror None facecolor or fc: :mpltype:coloror None figure:~matplotlib.figure.Figureor~matplotlib.figure.SubFigurefill: bool gid: str hatch: {'/', '\', '|', '-', '+', 'x', 'o', 'O', '.', '*'} hatch_linewidth: unknown in_layout: bool joinstyle:.JoinStyleor {'miter', 'round', 'bevel'} label: object linestyle or ls: {'-', '–', '-.', ':', '', (offset, on-off-seq), …} linewidth or lw: float or None mouseover: bool mutation_aspect: float mutation_scale: float patchA:.patches.PatchpatchB:.patches.Patchpath_effects: list of.AbstractPathEffectpicker: None or bool or float or callable positions: unknown rasterized: bool sketch_params: (scale: float, length: float, randomness: float) snap: bool or None transform:~matplotlib.transforms.Transformurl: str visible: bool zorder: float