VirtualMicrobes.my_tools package¶
Submodules¶
VirtualMicrobes.my_tools.analysis_tools module¶
Created on Dec 27, 2014
@author: thocu
-
VirtualMicrobes.my_tools.analysis_tools.
set_differences
(sets)[source]¶ Returns a measure of difference between sets in a Counter object
From the counter object, the n most frequent sets are extracted. Then, between each set and the remaining sets differences are computed and expressed as number of differing items for each pair compaired (all pairs formed by ‘it.combinations’). This number is then scaled to the maximum possible difference, which would be the combined number of items in both members of a pair.
Parameters: sets – (e.g. produced metabolites in a cell)
VirtualMicrobes.my_tools.monkey module¶
Created on Feb 17, 2016
@author: thocu
-
class
VirtualMicrobes.my_tools.monkey.
Artist
¶ Bases:
object
Abstract base class for someone who renders into a
FigureCanvas
.-
add_callback
(func)[source]¶ Adds a callback function that will be called whenever one of the
Artist
‘s properties changes.Returns an id that is useful for removing the callback with
remove_callback()
later.
-
aname
= u'Artist'¶
-
axes
¶ The
Axes
instance the artist resides in, or None.
-
contains
(mouseevent)[source]¶ Test whether the artist contains the mouse event.
Returns the truth value and a dictionary of artist specific details of selection, such as which points are contained in the pick radius. See individual artists for details.
-
convert_xunits
(x)[source]¶ For artists in an axes, if the xaxis has units support, convert x using xaxis unit type
-
convert_yunits
(y)[source]¶ For artists in an axes, if the yaxis has units support, convert y using yaxis unit type
-
findobj
(match=None, include_self=True)[source]¶ Find artist objects.
Recursively find all
Artist
instances contained in self.match can be
- None: return all objects contained in artist.
- function with signature
boolean = match(artist)
used to filter matches - class instance: e.g., Line2D. Only return artists of class type.
If include_self is True (default), include self in the list to be checked for a match.
-
get_axes
()[source]¶ Return the
Axes
instance the artist resides in, or None.This has been deprecated in mpl 1.5, please use the axes property. Will be removed in 1.7 or 2.0.
-
get_sketch_params
()[source]¶ Returns the sketch parameters for the artist.
Returns: - sketch_params (tuple or None)
- A 3-tuple with the following elements –
- scale: The amplitude of the wiggle perpendicular to the source line.
- length: The length of the wiggle along the line.
- randomness: The scale factor by which the length is shrunken or expanded.
- May return None if no sketch parameters were set.
-
get_snap
()[source]¶ Returns the snap setting which may be:
- True: snap vertices to the nearest pixel center
- False: leave vertices as-is
- None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center
Only supported by the Agg and MacOSX backends.
-
get_transformed_clip_path_and_affine
()[source]¶ Return the clip path with the non-affine part of its transformation applied, and the remaining affine part of its transformation.
-
get_window_extent
(renderer)[source]¶ Get the axes bounding box in display space. 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.
-
mouseover
¶
-
pick
(mouseevent)[source]¶ call signature:
pick(mouseevent)
each child artist will fire a pick event if mouseevent is over the artist and the artist has picker set
-
remove
()[source]¶ Remove the artist from the figure if possible. The effect will not be visible until the figure is redrawn, e.g., with
matplotlib.axes.Axes.draw_idle()
. Callmatplotlib.axes.Axes.relim()
to update the axes limits if desired.Note:
relim()
will not see collections even if the collection was added to axes with autolim = True.Note: there is no support for removing the artist’s legend entry.
-
remove_callback
(oid)[source]¶ Remove a callback based on its id.
See also
add_callback()
- For adding callbacks
-
set
(**kwargs)[source]¶ A property batch setter. Pass kwargs to set properties. Will handle property name collisions (e.g., if both ‘color’ and ‘facecolor’ are specified, the property with higher priority gets set last).
-
set_alpha
(alpha)[source]¶ Set the alpha value used for blending - not supported on all backends.
ACCEPTS: float (0.0 transparent through 1.0 opaque)
-
set_axes
(axes)[source]¶ Set the
Axes
instance in which the artist resides, if any.This has been deprecated in mpl 1.5, please use the axes property. Will be removed in 1.7 or 2.0.
ACCEPTS: an
Axes
instance
-
set_clip_box
(clipbox)[source]¶ Set the artist’s clip
Bbox
.ACCEPTS: a
matplotlib.transforms.Bbox
instance
-
set_clip_on
(b)[source]¶ Set whether artist uses clipping.
When False artists will be visible out side of the axes which can lead to unexpected results.
ACCEPTS: [True | False]
-
set_clip_path
(path, transform=None)[source]¶ Set the artist’s clip path, which may be:
a
Patch
(or subclass) instance- a
Path
instance, in which case an optional
Transform
instance may be provided, which will be applied to the path before using it for clipping.
- a
None, to remove the clipping path
For efficiency, if the path happens to be an axis-aligned rectangle, this method will set the clipping box to the corresponding rectangle and set the clipping path to None.
ACCEPTS: [ (
Path
,Transform
) |Patch
| None ]
-
set_contains
(picker)[source]¶ Replace the contains test used by this artist. The new picker should be a callable function which determines whether the artist is hit by the mouse event:
hit, props = picker(artist, mouseevent)
If the mouse event is over the artist, return hit = True and props is a dictionary of properties you want returned with the contains test.
ACCEPTS: a callable function
-
set_figure
(fig)[source]¶ Set the
Figure
instance the artist belongs to.ACCEPTS: a
matplotlib.figure.Figure
instance
-
set_label
(s)[source]¶ Set the label to s for auto legend.
ACCEPTS: string or anything printable with ‘%s’ conversion.
-
set_path_effects
(path_effects)[source]¶ set path_effects, which should be a list of instances of matplotlib.patheffect._Base class or its derivatives.
-
set_picker
(picker)[source]¶ Set the epsilon for picking used by this artist
picker can be one of the following:
None: picking is disabled for this artist (default)
A boolean: if True then picking will be enabled and the artist will fire a pick event if the mouse event is over the artist
A float: if picker is a number it is interpreted as an epsilon tolerance in points and the artist will fire off an event if it’s data is within epsilon of the mouse event. For some artists like lines and patch collections, the artist may provide additional data to the pick event that is generated, e.g., the indices of the data within epsilon of the pick event
A function: if picker is callable, it is a user supplied function which determines whether the artist is hit by the mouse event:
hit, props = picker(artist, mouseevent)
to determine the hit test. if the mouse event is over the artist, return hit=True and props is a dictionary of properties you want added to the PickEvent attributes.
ACCEPTS: [None|float|boolean|callable]
-
set_rasterized
(rasterized)[source]¶ Force rasterized (bitmap) drawing in vector backend output.
Defaults to None, which implies the backend’s default behavior
ACCEPTS: [True | False | None]
-
set_sketch_params
(scale=None, length=None, randomness=None)[source]¶ Sets the sketch parameters.
Parameters: - scale (float, optional) – The amplitude of the wiggle perpendicular to the source line, in pixels. If scale is None, or not provided, no sketch filter will be provided.
- length (float, optional) – The length of the wiggle along the line, in pixels (default 128.0)
- randomness (float, optional) – The scale factor by which the length is shrunken or expanded (default 16.0)
-
set_snap
(snap)[source]¶ Sets the snap setting which may be:
- True: snap vertices to the nearest pixel center
- False: leave vertices as-is
- None: (auto) If the path contains only rectilinear line segments, round to the nearest pixel center
Only supported by the Agg and MacOSX backends.
-
set_transform
(t)[source]¶ Set the
Transform
instance used by this artist.ACCEPTS:
Transform
instance
-
set_zorder
(level)[source]¶ Set the zorder for the artist. Artists with lower zorder values are drawn first.
ACCEPTS: any number
-
stale
¶ If the artist is ‘stale’ and needs to be re-drawn for the output to match the internal state of the artist.
-
zorder
= 0¶
-
-
class
VirtualMicrobes.my_tools.monkey.
Figure
(figsize=None, dpi=None, facecolor=None, edgecolor=None, linewidth=0.0, frameon=None, subplotpars=None, tight_layout=None)¶ Bases:
VirtualMicrobes.my_tools.monkey.Artist
The Figure instance supports callbacks through a callbacks attribute which is a
matplotlib.cbook.CallbackRegistry
instance. The events you can connect to are ‘dpi_changed’, and the callback will be called withfunc(fig)
where fig is theFigure
instance.- patch
- The figure patch is drawn by a
matplotlib.patches.Rectangle
instance - suppressComposite
- For multiple figure images, the figure will make composite images depending on the renderer option_image_nocomposite function. If suppressComposite is True|False, this will override the renderer.
-
add_axes
(*args, **kwargs)[source]¶ Add an axes at position rect [left, bottom, width, height] where all quantities are in fractions of figure width and height. kwargs are legal
Axes
kwargs plus projection which sets the projection type of the axes. (For backward compatibility,polar=True
may also be provided, which is equivalent toprojection='polar'
). Valid values for projection are: [u’aitoff’, u’hammer’, u’lambert’, u’mollweide’, u’polar’, u’rectilinear’]. Some of these projections support additional kwargs, which may be provided toadd_axes()
. Typical usage:rect = l,b,w,h fig.add_axes(rect) fig.add_axes(rect, frameon=False, axisbg='g') fig.add_axes(rect, polar=True) fig.add_axes(rect, projection='polar') fig.add_axes(ax)
If the figure already has an axes with the same parameters, then it will simply make that axes current and return it. If you do not want this behavior, e.g., you want to force the creation of a new Axes, you must use a unique set of args and kwargs. The axes
label
attribute has been exposed for this purpose. e.g., if you want two axes that are otherwise identical to be added to the figure, make sure you give them unique labels:fig.add_axes(rect, label='axes1') fig.add_axes(rect, label='axes2')
In rare circumstances, add_axes may be called with a single argument, an Axes instance already created in the present figure but not in the figure’s list of axes. For example, if an axes has been removed with
delaxes()
, it can be restored with:fig.add_axes(ax)
In all cases, the
Axes
instance will be returned.In addition to projection, the following kwargs are supported:
adjustable: [ ‘box’ | ‘datalim’ | ‘box-forced’] agg_filter: unknown alpha: float (0.0 transparent through 1.0 opaque) anchor: unknown animated: [True | False] aspect: unknown autoscale_on: unknown autoscalex_on: unknown autoscaley_on: unknown axes: anAxes
instance axes_locator: unknown axis_bgcolor: any matplotlib color - seecolors()
axisbelow: [ True | False ] clip_box: amatplotlib.transforms.Bbox
instance clip_on: [True | False] clip_path: [ (Path
,Transform
) |Patch
| None ] color_cycle: unknown contains: a callable function figure: unknown frame_on: [ True | False ] gid: an id string label: string or anything printable with ‘%s’ conversion. navigate: [ True | False ] navigate_mode: unknown path_effects: unknown picker: [None|float|boolean|callable] position: unknown rasterization_zorder: unknown rasterized: [True | False | None] sketch_params: unknown snap: unknown title: unknown transform:Transform
instance url: a url string visible: [True | False] xbound: unknown xlabel: unknown xlim: length 2 sequence of floats xmargin: unknown xscale: [u’linear’ | u’log’ | u’logit’ | u’symlog’] xticklabels: sequence of strings xticks: sequence of floats ybound: unknown ylabel: unknown ylim: length 2 sequence of floats ymargin: unknown yscale: [u’linear’ | u’log’ | u’logit’ | u’symlog’] yticklabels: sequence of strings yticks: sequence of floats zorder: any number
-
add_subplot
(*args, **kwargs)[source]¶ Add a subplot. Examples:
fig.add_subplot(111) # equivalent but more general fig.add_subplot(1,1,1) # add subplot with red background fig.add_subplot(212, axisbg='r') # add a polar subplot fig.add_subplot(111, projection='polar') # add Subplot instance sub fig.add_subplot(sub)
kwargs are legal
Axes
kwargs plus projection, which chooses a projection type for the axes. (For backward compatibility, polar=True may also be provided, which is equivalent to projection=’polar’). Valid values for projection are: [u’aitoff’, u’hammer’, u’lambert’, u’mollweide’, u’polar’, u’rectilinear’]. Some of these projections support additional kwargs, which may be provided toadd_axes()
.The
Axes
instance will be returned.If the figure already has a subplot with key (args, kwargs) then it will simply make that subplot current and return it.
See also
subplot()
for an explanation of the args.The following kwargs are supported:
adjustable: [ ‘box’ | ‘datalim’ | ‘box-forced’] agg_filter: unknown alpha: float (0.0 transparent through 1.0 opaque) anchor: unknown animated: [True | False] aspect: unknown autoscale_on: unknown autoscalex_on: unknown autoscaley_on: unknown axes: anAxes
instance axes_locator: unknown axis_bgcolor: any matplotlib color - seecolors()
axisbelow: [ True | False ] clip_box: amatplotlib.transforms.Bbox
instance clip_on: [True | False] clip_path: [ (Path
,Transform
) |Patch
| None ] color_cycle: unknown contains: a callable function figure: unknown frame_on: [ True | False ] gid: an id string label: string or anything printable with ‘%s’ conversion. navigate: [ True | False ] navigate_mode: unknown path_effects: unknown picker: [None|float|boolean|callable] position: unknown rasterization_zorder: unknown rasterized: [True | False | None] sketch_params: unknown snap: unknown title: unknown transform:Transform
instance url: a url string visible: [True | False] xbound: unknown xlabel: unknown xlim: length 2 sequence of floats xmargin: unknown xscale: [u’linear’ | u’log’ | u’logit’ | u’symlog’] xticklabels: sequence of strings xticks: sequence of floats ybound: unknown ylabel: unknown ylim: length 2 sequence of floats ymargin: unknown yscale: [u’linear’ | u’log’ | u’logit’ | u’symlog’] yticklabels: sequence of strings yticks: sequence of floats zorder: any number
-
autofmt_xdate
(bottom=0.2, rotation=30, ha=u'right')[source]¶ Date ticklabels often overlap, so it is useful to rotate them and right align them. Also, a common use case is a number of subplots with shared xaxes where the x-axis is date data. The ticklabels are often long, and it helps to rotate them on the bottom subplot and turn them off on other subplots, as well as turn off xlabels.
- bottom
- The bottom of the subplots for
subplots_adjust()
- rotation
- The rotation of the xtick labels
- ha
- The horizontal alignment of the xticklabels
-
axes
¶ Read-only – list of axes in Figure
-
clf
(keep_observers=False)[source]¶ Clear the figure.
Set keep_observers to True if, for example, a gui widget is tracking the axes in the figure.
-
colorbar
(mappable, cax=None, ax=None, use_gridspec=True, **kw)[source]¶ Create a colorbar for a ScalarMappable instance, mappable.
Documentation for the pylab thin wrapper:
Add a colorbar to a plot.
Function signatures for the
pyplot
interface; all but the first are also method signatures for thecolorbar()
method:colorbar(**kwargs) colorbar(mappable, **kwargs) colorbar(mappable, cax=cax, **kwargs) colorbar(mappable, ax=ax, **kwargs)
Parameters: *mappable* – the
Image
,ContourSet
, etc. to which the colorbar applies; this argument is mandatory for thecolorbar()
method but optional for thecolorbar()
function, which sets the default to the current image.Keyword Arguments: - *cax* – None | axes object into which the colorbar will be drawn
- *ax* – None | parent axes object(s) from which space for a new colorbar axes will be stolen. If a list of axes is given they will all be resized to make room for the colorbar axes.
- *use_gridspec* – False | If cax is None, a new cax is created as an instance of Axes. If ax is an instance of Subplot and use_gridspec is True, cax is created as an instance of Subplot using the grid_spec module.
Additional keyword arguments are of two kinds:
axes properties:
Property Description orientation vertical or horizontal fraction 0.15; fraction of original axes to use for colorbar pad 0.05 if vertical, 0.15 if horizontal; fraction of original axes between colorbar and new image axes shrink 1.0; fraction by which to shrink the colorbar aspect 20; ratio of long to short dimensions anchor (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal; the anchor point of the colorbar axes panchor (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal; the anchor point of the colorbar parent axes. If False, the parent axes’ anchor will be unchanged colorbar properties:
Property Description extend [ ‘neither’ | ‘both’ | ‘min’ | ‘max’ ] If not ‘neither’, make pointed end(s) for out-of- range values. These are set for a given colormap using the colormap set_under and set_over methods. extendfrac [ None | ‘auto’ | length | lengths ] If set to None, both the minimum and maximum triangular colorbar extensions with have a length of 5% of the interior colorbar length (this is the default setting). If set to ‘auto’, makes the triangular colorbar extensions the same lengths as the interior boxes (when spacing is set to ‘uniform’) or the same lengths as the respective adjacent interior boxes (when spacing is set to ‘proportional’). If a scalar, indicates the length of both the minimum and maximum triangular colorbar extensions as a fraction of the interior colorbar length. A two-element sequence of fractions may also be given, indicating the lengths of the minimum and maximum colorbar extensions respectively as a fraction of the interior colorbar length. extendrect [ False | True ] If False the minimum and maximum colorbar extensions will be triangular (the default). If True the extensions will be rectangular. spacing [ ‘uniform’ | ‘proportional’ ] Uniform spacing gives each discrete color the same space; proportional makes the space proportional to the data interval. ticks [ None | list of ticks | Locator object ] If None, ticks are determined automatically from the input. format [ None | format string | Formatter object ] If None, the ScalarFormatter
is used. If a format string is given, e.g., ‘%.3f’, that is used. An alternativeFormatter
object may be given instead.drawedges [ False | True ] If true, draw lines at color boundaries. The following will probably be useful only in the context of indexed colors (that is, when the mappable has norm=NoNorm()), or other unusual circumstances.
Property Description boundaries None or a sequence values None or a sequence which must be of length 1 less than the sequence of boundaries. For each region delimited by adjacent entries in boundaries, the color mapped to the corresponding value in values will be used. If mappable is a
ContourSet
, its extend kwarg is included automatically.Note that the shrink kwarg provides a simple way to keep a vertical colorbar, for example, from being taller than the axes of the mappable to which the colorbar is attached; but it is a manual method requiring some trial and error. If the colorbar is too tall (or a horizontal colorbar is too wide) use a smaller value of shrink.
For more precise control, you can manually specify the positions of the axes objects in which the mappable and the colorbar are drawn. In this case, do not use any of the axes properties kwargs.
It is known that some vector graphics viewer (svg and pdf) renders white gaps between segments of the colorbar. This is due to bugs in the viewers not matplotlib. As a workaround the colorbar can be rendered with overlapping segments:
cbar = colorbar() cbar.solids.set_edgecolor("face") draw()
However this has negative consequences in other circumstances. Particularly with semi transparent images (alpha < 1) and colorbar extensions and is not enabled by default see (issue #1188).
Returns: Colorbar
instance; see also its base class,ColorbarBase
. Call theset_label()
method to label the colorbar.
-
dpi
¶
-
draw
(artist, renderer, *args, **kwargs)¶ Render the figure using
matplotlib.backend_bases.RendererBase
instance renderer.
-
draw_artist
(a)[source]¶ draw
matplotlib.artist.Artist
instance a only – this is available only after the figure is drawn
-
figimage
(X, xo=0, yo=0, alpha=None, norm=None, cmap=None, vmin=None, vmax=None, origin=None, resize=False, **kwargs)[source]¶ Adds a non-resampled image to the figure.
call signatures:
figimage(X, **kwargs)
adds a non-resampled array X to the figure.
figimage(X, xo, yo)
with pixel offsets xo, yo,
X must be a float array:
- If X is MxN, assume luminance (grayscale)
- If X is MxNx3, assume RGB
- If X is MxNx4, assume RGBA
Optional keyword arguments:
Keyword Description resize a boolean, True or False. If “True”, then re-size the Figure to match the given image size. xo or yo An integer, the x and y image offset in pixels cmap a matplotlib.colors.Colormap
instance, e.g., cm.jet. If None, default to the rcimage.cmap
valuenorm a matplotlib.colors.Normalize
instance. The default is normalization(). This scales luminance -> 0-1vmin|vmax are used to scale a luminance image to 0-1. If either is None, the min and max of the luminance values will be used. Note if you pass a norm instance, the settings for vmin and vmax will be ignored. alpha the alpha blending value, default is None origin [ ‘upper’ | ‘lower’ ] Indicates where the [0,0] index of the array is in the upper left or lower left corner of the axes. Defaults to the rc image.origin value figimage complements the axes image (
imshow()
) which will be resampled to fit the current axes. If you want a resampled image to fill the entire figure, you can define anAxes
with size [0,1,0,1].An
matplotlib.image.FigureImage
instance is returned.Additional kwargs are Artist kwargs passed on to
FigureImage
-
gca
(**kwargs)[source]¶ Get the current axes, creating one if necessary
The following kwargs are supported for ensuring the returned axes adheres to the given projection etc., and for axes creation if the active axes does not exist:
adjustable: [ ‘box’ | ‘datalim’ | ‘box-forced’] agg_filter: unknown alpha: float (0.0 transparent through 1.0 opaque) anchor: unknown animated: [True | False] aspect: unknown autoscale_on: unknown autoscalex_on: unknown autoscaley_on: unknown axes: anAxes
instance axes_locator: unknown axis_bgcolor: any matplotlib color - seecolors()
axisbelow: [ True | False ] clip_box: amatplotlib.transforms.Bbox
instance clip_on: [True | False] clip_path: [ (Path
,Transform
) |Patch
| None ] color_cycle: unknown contains: a callable function figure: unknown frame_on: [ True | False ] gid: an id string label: string or anything printable with ‘%s’ conversion. navigate: [ True | False ] navigate_mode: unknown path_effects: unknown picker: [None|float|boolean|callable] position: unknown rasterization_zorder: unknown rasterized: [True | False | None] sketch_params: unknown snap: unknown title: unknown transform:Transform
instance url: a url string visible: [True | False] xbound: unknown xlabel: unknown xlim: length 2 sequence of floats xmargin: unknown xscale: [u’linear’ | u’log’ | u’logit’ | u’symlog’] xticklabels: sequence of strings xticks: sequence of floats ybound: unknown ylabel: unknown ylim: length 2 sequence of floats ymargin: unknown yscale: [u’linear’ | u’log’ | u’logit’ | u’symlog’] yticklabels: sequence of strings yticks: sequence of floats zorder: any number
-
get_size_inches
()[source]¶ Returns the current size of the figure in inches (1in == 2.54cm) as an numpy array.
Returns: size – The size of the figure in inches Return type: ndarray See also
matplotlib.Figure.set_size_inches()
-
get_tightbbox
(renderer)[source]¶ Return a (tight) bounding box of the figure in inches.
It only accounts axes title, axis labels, and axis ticklabels. Needs improvement.
-
get_window_extent
(*args, **kwargs)[source]¶ get the figure bounding box in display space; kwargs are void
-
ginput
(n=1, timeout=30, show_clicks=True, mouse_add=1, mouse_pop=3, mouse_stop=2)[source]¶ Call signature:
ginput(self, n=1, timeout=30, show_clicks=True, mouse_add=1, mouse_pop=3, mouse_stop=2)
Blocking call to interact with the figure.
This will wait for n clicks from the user and return a list of the coordinates of each click.
If timeout is zero or negative, does not timeout.
If n is zero or negative, accumulate clicks until a middle click (or potentially both mouse buttons at once) terminates the input.
Right clicking cancels last input.
The buttons used for the various actions (adding points, removing points, terminating the inputs) can be overriden via the arguments mouse_add, mouse_pop and mouse_stop, that give the associated mouse button: 1 for left, 2 for middle, 3 for right.
The keyboard can also be used to select points in case your mouse does not have one or more of the buttons. The delete and backspace keys act like right clicking (i.e., remove last point), the enter key terminates input and any other key (not already used by the window manager) selects a point.
-
hold
(b=None)[source]¶ Set the hold state. If hold is None (default), toggle the hold state. Else set the hold state to boolean value b.
e.g.:
hold() # toggle hold hold(True) # hold is on hold(False) # hold is off
-
legend
(handles, labels, *args, **kwargs)[source]¶ Place a legend in the figure. Labels are a sequence of strings, handles is a sequence of
Line2D
orPatch
instances, and loc can be a string or an integer specifying the legend locationUSAGE:
legend( (line1, line2, line3), ('label1', 'label2', 'label3'), 'upper right')
The loc location codes are:
'best' : 0, (currently not supported for figure legends) 'upper right' : 1, 'upper left' : 2, 'lower left' : 3, 'lower right' : 4, 'right' : 5, 'center left' : 6, 'center right' : 7, 'lower center' : 8, 'upper center' : 9, 'center' : 10,
loc can also be an (x,y) tuple in figure coords, which specifies the lower left of the legend box. figure coords are (0,0) is the left, bottom of the figure and 1,1 is the right, top.
Keyword Arguments: - *prop* – [ None | FontProperties | dict ]
A
matplotlib.font_manager.FontProperties
instance. If prop is a dictionary, a new instance will be created with prop. If None, use rc settings. - *numpoints* – integer The number of points in the legend line, default is 4
- *scatterpoints* – integer The number of points in the legend line, default is 4
- *scatteryoffsets* – list of floats a list of yoffsets for scatter symbols in legend
- *markerscale* – [ None | scalar ] The relative size of legend markers vs. original. If None, use rc settings.
- *markerfirst* – [ True | False ] if True, legend marker is placed to the left of the legend label if False, legend marker is placed to the right of the legend label
- *fancybox* – [ None | False | True ] if True, draw a frame with a round fancybox. If None, use rc
- *shadow* – [ None | False | True ] If True, draw a shadow behind legend. If None, use rc settings.
- *ncol* – integer number of columns. default is 1
- *mode* – [ “expand” | None ] if mode is “expand”, the legend will be horizontally expanded to fill the axes area (or bbox_to_anchor)
- *title* – string the legend title
Padding and spacing between various elements use following keywords parameters. The dimensions of these values are given as a fraction of the fontsize. Values from rcParams will be used if None.
Keyword Description borderpad the fractional whitespace inside the legend border labelspacing the vertical space between the legend entries handlelength the length of the legend handles handletextpad the pad between the legend handle and text borderaxespad the pad between the axes and legend border columnspacing the spacing between columns Note
Not all kinds of artist are supported by the legend. See LINK (FIXME) for details.
Example:
- *prop* – [ None | FontProperties | dict ]
A
-
savefig
(*args, **kwargs)[source]¶ Save the current figure.
Call signature:
savefig(fname, dpi=None, facecolor='w', edgecolor='w', orientation='portrait', papertype=None, format=None, transparent=False, bbox_inches=None, pad_inches=0.1, frameon=None)
The output formats available depend on the backend being used.
Parameters: *fname* –
A string containing a path to a filename, or a Python file-like object, or possibly some backend-dependent object such as
PdfPages
.If format is None and fname is a string, the output format is deduced from the extension of the filename. If the filename has no extension, the value of the rc parameter
savefig.format
is used.If fname is not a string, remember to specify format to ensure that the correct backend is used.
Keyword Arguments: - *dpi* – [ None |
scalar > 0
| ‘figure’] The resolution in dots per inch. If None it will default to the valuesavefig.dpi
in the matplotlibrc file. If ‘figure’ it will set the dpi to be the value of the figure. - *facecolor*, *edgecolor* – the colors of the figure rectangle
- *orientation* – [ ‘landscape’ | ‘portrait’ ] not supported on all backends; currently only on postscript output
- *papertype* – One of ‘letter’, ‘legal’, ‘executive’, ‘ledger’, ‘a0’ through ‘a10’, ‘b0’ through ‘b10’. Only supported for postscript output.
- *format* – One of the file extensions supported by the active backend. Most backends support png, pdf, ps, eps and svg.
- *transparent* – If True, the axes patches will all be transparent; the figure patch will also be transparent unless facecolor and/or edgecolor are specified via kwargs. This is useful, for example, for displaying a plot on top of a colored background on a web page. The transparency of these patches will be restored to their original values upon exit of this function.
- *frameon* – If True, the figure patch will be colored, if False, the figure background will be transparent. If not provided, the rcParam ‘savefig.frameon’ will be used.
- *bbox_inches* – Bbox in inches. Only the given portion of the figure is saved. If ‘tight’, try to figure out the tight bbox of the figure.
- *pad_inches* – Amount of padding around the figure when bbox_inches is ‘tight’.
- *bbox_extra_artists* – A list of extra artists that will be considered when the tight bbox is calculated.
- *dpi* – [ None |
-
set_canvas
(canvas)[source]¶ Set the canvas that contains the figure
ACCEPTS: a FigureCanvas instance
-
set_edgecolor
(color)[source]¶ Set the edge color of the Figure rectangle
ACCEPTS: any matplotlib color - see help(colors)
-
set_facecolor
(color)[source]¶ Set the face color of the Figure rectangle
ACCEPTS: any matplotlib color - see help(colors)
-
set_frameon
(b)[source]¶ Set whether the figure frame (background) is displayed or invisible
ACCEPTS: boolean
-
set_size_inches
(w, h, forward=False)[source]¶ Set the figure size in inches (1in == 2.54cm)
Usage:
fig.set_size_inches(w,h) # OR fig.set_size_inches((w,h) )
optional kwarg forward=True will cause the canvas size to be automatically updated; e.g., you can resize the figure window from the shell
ACCEPTS: a w,h tuple with w,h in inches
See also
matplotlib.Figure.get_size_inches()
-
set_tight_layout
(tight)[source]¶ Set whether
tight_layout()
is used upon drawing. If None, the rcParams[‘figure.autolayout’] value will be set.When providing a dict containing the keys pad, w_pad, h_pad and rect, the default
tight_layout()
paddings will be overridden.ACCEPTS: [True | False | dict | None ]
-
show
(warn=True)[source]¶ If using a GUI backend with pyplot, display the figure window.
If the figure was not created using
figure()
, it will lack aFigureManagerBase
, and will raise an AttributeError.For non-GUI backends, this does nothing, in which case a warning will be issued if warn is True (default).
-
subplots_adjust
(*args, **kwargs)[source]¶ Call signature:
subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=None, hspace=None)
Update the
SubplotParams
with kwargs (defaulting to rc when None) and update the subplot locations
-
suptitle
(t, **kwargs)[source]¶ Add a centered title to the figure.
kwargs are
matplotlib.text.Text
properties. Using figure coordinates, the defaults are:- x : 0.5
- The x location of the text in figure coords
- y : 0.98
- The y location of the text in figure coords
- horizontalalignment : ‘center’
- The horizontal alignment of the text
- verticalalignment : ‘top’
- The vertical alignment of the text
A
matplotlib.text.Text
instance is returned.Example:
fig.suptitle('this is the figure title', fontsize=12)
-
text
(x, y, s, *args, **kwargs)[source]¶ Add text to figure.
Call signature:
text(x, y, s, fontdict=None, **kwargs)
Add text to figure at location x, y (relative 0-1 coords). See
text()
for the meaning of the other arguments.kwargs control the
Text
properties:agg_filter: unknown alpha: float (0.0 transparent through 1.0 opaque) animated: [True | False] axes: anAxes
instance backgroundcolor: any matplotlib color bbox: FancyBboxPatch prop dict clip_box: amatplotlib.transforms.Bbox
instance clip_on: [True | False] clip_path: [ (Path
,Transform
) |Patch
| None ] color: any matplotlib color contains: a callable function family or fontfamily or fontname or name: [FONTNAME | ‘serif’ | ‘sans-serif’ | ‘cursive’ | ‘fantasy’ | ‘monospace’ ] figure: amatplotlib.figure.Figure
instance fontproperties or font_properties: amatplotlib.font_manager.FontProperties
instance gid: an id string horizontalalignment or ha: [ ‘center’ | ‘right’ | ‘left’ ] label: string or anything printable with ‘%s’ conversion. linespacing: float (multiple of font size) multialignment: [‘left’ | ‘right’ | ‘center’ ] path_effects: unknown picker: [None|float|boolean|callable] position: (x,y) rasterized: [True | False | None] rotation: [ angle in degrees | ‘vertical’ | ‘horizontal’ ] rotation_mode: unknown size or fontsize: [size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ | ‘xx-large’ ] sketch_params: unknown snap: unknown stretch or fontstretch: [a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘condensed’ | ‘semi-condensed’ | ‘normal’ | ‘semi-expanded’ | ‘expanded’ | ‘extra-expanded’ | ‘ultra-expanded’ ] style or fontstyle: [ ‘normal’ | ‘italic’ | ‘oblique’] text: string or anything printable with ‘%s’ conversion. transform:Transform
instance url: a url string usetex: unknown variant or fontvariant: [ ‘normal’ | ‘small-caps’ ] verticalalignment or va or ma: [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ] visible: [True | False] weight or fontweight: [a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | ‘book’ | ‘medium’ | ‘roman’ | ‘semibold’ | ‘demibold’ | ‘demi’ | ‘bold’ | ‘heavy’ | ‘extra bold’ | ‘black’ ] wrap: unknown x: float y: float zorder: any number
-
tight_layout
(renderer=None, pad=1.08, h_pad=None, w_pad=None, rect=None)[source]¶ Adjust subplot parameters to give specified padding.
Parameters: - *pad* – float padding between the figure edge and the edges of subplots, as a fraction of the font-size.
- w_pad (*h_pad*,) – float padding (height/width) between edges of adjacent subplots. Defaults to pad_inches.
- *rect* – if rect is given, it is interpreted as a rectangle (left, bottom, right, top) in the normalized figure coordinate that the whole subplots area (including labels) will fit into. Default is (0, 0, 1, 1).
Call signature:
waitforbuttonpress(self, timeout=-1)
Blocking call to interact with the figure.
This will return True is a key was pressed, False if a mouse button was pressed and None if timeout was reached without either being pressed.
If timeout is negative, does not timeout.
-
VirtualMicrobes.my_tools.monkey.
MyTransformWrapper
[source]¶ alias of
TransformWrapper
-
class
VirtualMicrobes.my_tools.monkey.
TransformWrapper
(child)¶ Bases:
matplotlib.transforms.Transform
A helper class that holds a single child transform and acts equivalently to it.
This is useful if a node of the transform tree must be replaced at run time with a transform of a different type. This class allows that replacement to correctly trigger invalidation.
Note that
TransformWrapper
instances must have the same input and output dimensions during their entire lifetime, so the child transform may only be replaced with another child transform of the same dimensions.-
frozen
()[source]¶ Returns a frozen copy of this transform node. The frozen copy will not update when its children change. Useful for storing a previously known state of a transform where
copy.deepcopy()
might normally be used.
-
has_inverse
¶
-
is_affine
¶
-
is_separable
¶
-
pass_through
= True¶
-
-
VirtualMicrobes.my_tools.monkey.
monkeypatch_class
(name, bases, namespace)[source]¶ https://mail.python.org/pipermail/python-dev/2008-January/076194.html
WHOOOHHHAAAAA this is a Monkey Patch. Eat that, unreliable package developers!
VirtualMicrobes.my_tools.utility module¶
Created on Oct 22, 2014
@author: thocu
-
class
VirtualMicrobes.my_tools.utility.
CircularList
[source]¶ Bases:
list
A list that wraps around instead of throwing an index error.
Works like a regular list: >>> cl = CircularList([1,2,3]) >>> cl [1, 2, 3] >>> cl[0] 1 >>> cl[-1] 3 >>> cl[2] 3 Except wraps around: >>> cl[3] 1 >>> cl[-4] 3 Slices work >>> cl[0:2]
-
class
VirtualMicrobes.my_tools.utility.
Consumer
(task_queue, result_queue, task_timeout=120)[source]¶ Bases:
multiprocessing.process.Process
Consumer Process that gets jobs from a Queue until receiving a ‘poison pill’ job that will terminate the process.
Jobs will timeout after a given time.
-
class
VirtualMicrobes.my_tools.utility.
Coord
(x, y)¶ Bases:
tuple
-
x
¶ Alias for field number 0
-
y
¶ Alias for field number 1
-
-
class
VirtualMicrobes.my_tools.utility.
ETEtreeStruct
(tree, named_node_dict, node_name_to_phylo_node)¶ Bases:
tuple
-
named_node_dict
¶ Alias for field number 1
-
node_name_to_phylo_node
¶ Alias for field number 2
-
tree
¶ Alias for field number 0
-
-
class
VirtualMicrobes.my_tools.utility.
FIFOLarder
(filename, flag='c', protocol=None)[source]¶ Bases:
shelve.Shelf
Maintain a hybrid cached/pickled dictionary that presents as a normal dictionary. Postpone pickling of dictionary values until (partial)sync calls. This requires both the pickled and the cached dict to be checked when lookup en set operations are applied. The cache is an OrderedDict so that it can be ‘partially’ synced to pickle in FIFO order. This structure is usefull when new data coming in is still handled often and may regularly change, while old data can be considered more stable and less likely to change, and thus amenable for more permanent storage.
-
class
VirtualMicrobes.my_tools.utility.
FormatMessageFile
(name, mode='r', replace_dict={'x08': '', 'r': 'n', '\x1b\[([0-9, A-Z]{1, 2}(;[0-9]{1, 2})?(;[0-9]{3})?)?[m|K]?': ''}, **kwargs)[source]¶ Bases:
file
-
class
VirtualMicrobes.my_tools.utility.
GeneProduct
(*iargs, **ikwargs)¶ Bases:
object
-
concentration
¶
-
cum_time_course
¶
-
degradation
¶
-
diffusion
¶
-
multiplicity
¶
-
time_course
¶
-
-
class
VirtualMicrobes.my_tools.utility.
GeneTypeNumbers
(tf, enz, pump)¶ Bases:
tuple
-
enz
¶ Alias for field number 1
-
pump
¶ Alias for field number 2
-
tf
¶ Alias for field number 0
-
-
class
VirtualMicrobes.my_tools.utility.
GridPos
(row, col)¶ Bases:
tuple
-
col
¶ Alias for field number 1
-
row
¶ Alias for field number 0
-
-
class
VirtualMicrobes.my_tools.utility.
GridSubDiv
(row, col)¶ Bases:
tuple
-
col
¶ Alias for field number 1
-
row
¶ Alias for field number 0
-
-
class
VirtualMicrobes.my_tools.utility.
LinkThroughSequence
(data=[])[source]¶ Bases:
list
A list that applies an arbitrary element function before returning and storing
-
class
VirtualMicrobes.my_tools.utility.
LinkThroughSet
(data=[])[source]¶ Bases:
set
A dictionary that applies an arbitrary key-altering function before accessing the keys
-
class
VirtualMicrobes.my_tools.utility.
MutationParamSpace
(base, lower, upper, min, max)¶ Bases:
tuple
-
base
¶ Alias for field number 0
-
lower
¶ Alias for field number 1
-
max
¶ Alias for field number 4
-
min
¶ Alias for field number 3
-
upper
¶ Alias for field number 2
-
-
class
VirtualMicrobes.my_tools.utility.
MutationRates
(chrom_dup, chrom_del, chrom_fiss, chrom_fuse, point_mutation, tandem_dup, stretch_del, stretch_invert, stretch_translocate, stretch_exp_lambda, external_hgt, internal_hgt, regulatory_mutation, reg_stretch_exp_lambda)¶ Bases:
tuple
-
chrom_del
¶ Alias for field number 1
-
chrom_dup
¶ Alias for field number 0
-
chrom_fiss
¶ Alias for field number 2
-
chrom_fuse
¶ Alias for field number 3
-
external_hgt
¶ Alias for field number 10
-
internal_hgt
¶ Alias for field number 11
-
point_mutation
¶ Alias for field number 4
-
reg_stretch_exp_lambda
¶ Alias for field number 13
-
regulatory_mutation
¶ Alias for field number 12
-
stretch_del
¶ Alias for field number 6
-
stretch_exp_lambda
¶ Alias for field number 9
-
stretch_invert
¶ Alias for field number 7
-
stretch_translocate
¶ Alias for field number 8
-
tandem_dup
¶ Alias for field number 5
-
-
class
VirtualMicrobes.my_tools.utility.
OrderedDefaultdict
(*args, **kwargs)[source]¶ Bases:
collections.OrderedDict
-
class
VirtualMicrobes.my_tools.utility.
ParamSpace
(base, lower, upper)¶ Bases:
tuple
-
base
¶ Alias for field number 0
-
lower
¶ Alias for field number 1
-
upper
¶ Alias for field number 2
-
-
class
VirtualMicrobes.my_tools.utility.
PartialLinkThroughDict
(linker_dict, *args, **kwargs)[source]¶ Bases:
_abcoll.MutableMapping
Values objects can have a ‘_unique_key’ attribute, in which case storage of the value is linked through to the linker_dict. Otherwise, the value goes into the local storage of the PartialLinkThroughDict instance.
-
class
VirtualMicrobes.my_tools.utility.
PointMutationRatios
(v_max, ene_ks, subs_ks, exporting, promoter, operator, eff_bound, eff_apo, ligand_ks, k_bind_op, ligand_class, bind, sense_external)¶ Bases:
tuple
-
bind
¶ Alias for field number 11
-
eff_apo
¶ Alias for field number 7
-
eff_bound
¶ Alias for field number 6
-
ene_ks
¶ Alias for field number 1
-
exporting
¶ Alias for field number 3
-
k_bind_op
¶ Alias for field number 9
-
ligand_class
¶ Alias for field number 10
-
ligand_ks
¶ Alias for field number 8
-
operator
¶ Alias for field number 5
-
promoter
¶ Alias for field number 4
-
sense_external
¶ Alias for field number 12
-
subs_ks
¶ Alias for field number 2
-
v_max
¶ Alias for field number 0
-
-
class
VirtualMicrobes.my_tools.utility.
PopulationWipe
(interval, fraction)¶ Bases:
tuple
-
fraction
¶ Alias for field number 1
-
interval
¶ Alias for field number 0
-
-
class
VirtualMicrobes.my_tools.utility.
ReactionScheme
(reactants, products)¶ Bases:
tuple
-
products
¶ Alias for field number 1
-
reactants
¶ Alias for field number 0
-
-
class
VirtualMicrobes.my_tools.utility.
RegulatorytMutationRatios
(translocate, random_insert)¶ Bases:
tuple
-
random_insert
¶ Alias for field number 1
-
translocate
¶ Alias for field number 0
-
-
class
VirtualMicrobes.my_tools.utility.
ReusableIndexDict
(keys=[], fixed_length=None, randomized=True)[source]¶ Bases:
object
-
class_version
= '0.0'¶
-
upgrade
()[source]¶ Upgrading from older pickled version of class to latest version. Version information is saved as class variable and should be updated when class invariants (e.g. fields) are added. Adapted from recipe at http://code.activestate.com/recipes/521901-upgradable-pickles/
-
-
class
VirtualMicrobes.my_tools.utility.
SmallMol
(*iargs, **ikwargs)¶ Bases:
object
-
concentration
¶
-
cum_time_course
¶
-
degradation
¶
-
diffusion
¶
-
influx
¶
-
time_course
¶
-
-
class
VirtualMicrobes.my_tools.utility.
SubEnv
(influx_dict, sub_grid)¶ Bases:
tuple
-
influx_dict
¶ Alias for field number 0
-
sub_grid
¶ Alias for field number 1
-
-
class
VirtualMicrobes.my_tools.utility.
Task
(obj, func_name, args=[], kwargs={})[source]¶ Bases:
object
Task object class used to present jobs to Consumer processes. Tasks are assumed to be method functions associated with a class instance.
Task will except all errors generated by the method call so that the Consumer processing the Task will stay alive.
-
VirtualMicrobes.my_tools.utility.
detect_rel_path_change
(old_save_dir, load_file, mount_path_depth=4, abs_root='/linuxhome/tmp/')[source]¶ Detects the usage of a mounted path versus the abolute path on the server.
- old_save_dir : path
- Original simulation save path
- load_file : file_path
- Full path of the load file
mount_path_depth : path
Parameters: abs_root –
-
VirtualMicrobes.my_tools.utility.
detect_sim_folder_move
(stored_save_dir, load_path)[source]¶ Detect whether the load_path was placed in a different location from the original simulation path.
Parameters: - stored_save_dir (path) – original simulation directory
- load_path (path) – load file
-
VirtualMicrobes.my_tools.utility.
map_backward_func
(key)¶
-
VirtualMicrobes.my_tools.utility.
map_forward_func
(val)¶
-
VirtualMicrobes.my_tools.utility.
namedtuple_with_defaults
(typename, field_names, default_values=())[source]¶
-
class
VirtualMicrobes.my_tools.utility.
pickles_adict
(*args, **kwargs)[source]¶ Bases:
attrdict.AttrDict
-
VirtualMicrobes.my_tools.utility.
processify
(func)[source]¶ Decorator to run a function as a process.
Be sure that every argument and the return value is pickable. The created process is joined, so the code does not run in parallel.
-
VirtualMicrobes.my_tools.utility.
queuedprocessor
(as_subprocess=True)[source]¶ Decorator that can can cause a decorated method to be returned as a Task tuple, depending on the decorator argument.
-
VirtualMicrobes.my_tools.utility.
same_content
(dir1, dir2)[source]¶ Compare two directory trees content. Return False if they differ, True if they are the same.
-
VirtualMicrobes.my_tools.utility.
save_simprocessify_func
(q, *args, **kwargs)¶
-
VirtualMicrobes.my_tools.utility.
sdi
(data)[source]¶ Given a hash { ‘species’: count } , returns the SDI
>>> sdi({'a': 10, 'b': 20, 'c': 30,}) 1.0114042647073518
-
VirtualMicrobes.my_tools.utility.
subprocessor
(as_subprocess=True)[source]¶ Decorator that can can cause a decorated function or method to be returned as a subprocess or simply evaluated, depending on the decorator argument.