Dans_Diffraction.functions_plotting (version 2.2)
index
c:\users\grp66007\onedrive - diamond light source ltd\pythonprojects\dans_diffraction\dans_diffraction\functions_plotting.py

Module: Handy plotting functions "functions_plotting.py"
 
Contains various plotting shortcuts using matplotlib.pyplot
 
By Dan Porter, PhD
Diamond
2018
 
Usage: 
    - Run this file in an interactive console
    OR
    - from Dans_Diffraction import functions_plotting as fp
 
All plots generated require plt.show() call, unless using interactive mode
 
 
Version 2.2
Last updated: 09/07/23
 
Version History:
06/01/18 1.0    Program created from DansGeneralProgs.py V2.3
05/03/18 1.1    Removed plt.show from arrow functions
17/04/18 1.2    Removed plt.show from other functions
03/05/18 1.3    Removed plot_vector_lines(vec_a,vec_b), replaced with plot_lattice_lines(Q, vec_a, vec_b)
30/05/18 1.4    Added multiplot
07/03/19 1.5    Added plot_attenuation and others
22/03/19 1.6    Added plot_circle, updated vecplot and plot_lattice_lines
03/05/19 1.7    Added legend to labels function
09/03/20 1.8    Added default figure size
22/11/20 1.9    Update to labels to fix 3D plotting
15/02/21 1.9.1  Update to vecplot for plotting on axis
27/09/21 2.0    Added plot3darray, plot_diffractometer_reciprocal_space
10/08/22 2.1    Added plot_lattice_points3D, set_plot_defaults, changed default fig size
09/07/23 2.2    Thanks to asteppke for suggested update to Arrow3D for matplotlib V>3.4
 
@author: DGPorter

 
Modules
       
Dans_Diffraction.functions_crystallography
Dans_Diffraction.functions_general
numpy
os
matplotlib.pyplot
mpl_toolkits.mplot3d.proj3d
sys

 
Classes
       
matplotlib.patches.FancyArrowPatch(matplotlib.patches.Patch)
Arrow3D

 
class Arrow3D(matplotlib.patches.FancyArrowPatch)
    Arrow3D(xs, ys, zs, *args, **kwargs)
 
FancyArrow3D patch for 3D arrows, by CT Zhu
 http://stackoverflow.com/questions/22867620/putting-arrowheads-on-vectors-in-matplotlibs-3d-plot
Useage:
  fig = plt.figure()
  ax = fig.add_subplot(111, projection='3d')
  ax.plot([0,1],[0,0],[0,0],'k-')
  ax.plot([0,0],[0,1],[0,0],'k-')
  ax.plot([0,0],[0,0],[0,1],'k-')
  v = Arrow3D([0,1],[0,1],[0,1], mutation_scale=20, lw=3, arrowstyle="-|>", color="r")
  ax.add_artist(v)
 
 
Method resolution order:
Arrow3D
matplotlib.patches.FancyArrowPatch
matplotlib.patches.Patch
matplotlib.artist.Artist
builtins.object

Methods defined here:
__init__(self, xs, ys, zs, *args, **kwargs)
If *posA* and *posB* are given, a path connecting two points is
created according to *connectionstyle*. The path will be
clipped with *patchA* and *patchB* and further shrunken by
*shrinkA* and *shrinkB*. An arrow is drawn along this
resulting path using the *arrowstyle* parameter.
 
Alternatively if *path* is provided, an arrow is drawn along this path
and *patchA*, *patchB*, *shrinkA*, and *shrinkB* are ignored.
 
Parameters
----------
 
posA, posB : None, tuple, optional (default: None)
    (x,y) coordinates of arrow tail and arrow head respectively.
 
path : None, Path (default: None)
    :class:`matplotlib.path.Path` instance. If provided, an arrow is
    drawn along this path and *patchA*, *patchB*, *shrinkA*, and
    *shrinkB* are ignored.
 
arrowstyle : str or ArrowStyle, optional (default: 'simple')
    Describes how the fancy arrow will be
    drawn. It can be string of the available arrowstyle names,
    with optional comma-separated attributes, or an
    :class:`ArrowStyle` instance. The optional attributes are meant to
    be scaled with the *mutation_scale*. The following arrow styles are
    available:
 
    
  =============   ==========   ==========================================================================
  Class           Name         Attrs                                                                     
  =============   ==========   ==========================================================================
  Curve           ``-``        None                                                                      
  CurveB          ``->``       head_length=0.4, head_width=0.2                                           
  BracketB        ``-[``       widthB=1.0, lengthB=0.2, angleB=None                                      
  CurveFilledB    ``-|>``      head_length=0.4, head_width=0.2                                           
  CurveA          ``<-``       head_length=0.4, head_width=0.2                                           
  CurveAB         ``<->``      head_length=0.4, head_width=0.2                                           
  CurveFilledA    ``<|-``      head_length=0.4, head_width=0.2                                           
  CurveFilledAB   ``<|-|>``    head_length=0.4, head_width=0.2                                           
  BracketA        ``]-``       widthA=1.0, lengthA=0.2, angleA=None                                      
  BracketAB       ``]-[``      widthA=1.0, lengthA=0.2, angleA=None, widthB=1.0, lengthB=0.2, angleB=None
  Fancy           ``fancy``    head_length=0.4, head_width=0.4, tail_width=0.4                           
  Simple          ``simple``   head_length=0.5, head_width=0.5, tail_width=0.2                           
  Wedge           ``wedge``    tail_width=0.3, shrink_factor=0.5                                         
  BarAB           ``|-|``      widthA=1.0, angleA=None, widthB=1.0, angleB=None                          
  =============   ==========   ==========================================================================
 
 
arrow_transmuter
    Ignored
 
connectionstyle : str, ConnectionStyle, or None, optional
(default: 'arc3')
    Describes how *posA* and *posB* are connected. It can be an
    instance of the :class:`ConnectionStyle` class or a string of the
    connectionstyle name, with optional comma-separated attributes. The
    following connection styles are available:
 
    
  ======   ==========   =================================================
  Class    Name         Attrs                                            
  ======   ==========   =================================================
  Angle    ``angle``    angleA=90, angleB=0, rad=0.0                     
  Angle3   ``angle3``   angleA=90, angleB=0                              
  Arc      ``arc``      angleA=0, angleB=0, armA=None, armB=None, rad=0.0
  Arc3     ``arc3``     rad=0.0                                          
  Bar      ``bar``      armA=0.0, armB=0.0, fraction=0.3, angle=None     
  ======   ==========   =================================================
 
 
connector
    Ignored
 
patchA, patchB : None, Patch, optional (default: None)
    Head and tail patch respectively. :class:`matplotlib.patch.Patch`
    instance.
 
shrinkA, shrinkB : scalar, optional (default: 2)
    Shrinking factor of the tail and head of the arrow respectively
 
mutation_scale : scalar, optional (default: 1)
    Value with which attributes of *arrowstyle* (e.g., *head_length*)
    will be scaled.
 
mutation_aspect : None, scalar, optional (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.
 
dpi_cor : scalar, optional (default: 1)
    dpi_cor is currently used for linewidth-related things and shrink
    factor. Mutation scale is affected by this.
 
Notes
-----
Valid kwargs are:
  agg_filter: a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
  alpha: float or None
  animated: bool
  antialiased or aa: unknown
  capstyle: {'butt', 'round', 'projecting'}
  clip_box: `.Bbox`
  clip_on: bool
  clip_path: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None]
  color: color
  contains: callable
  edgecolor or ec: color or None or 'auto'
  facecolor or fc: color or None
  figure: `.Figure`
  fill: bool
  gid: str
  hatch: {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
  in_layout: bool
  joinstyle: {'miter', 'round', 'bevel'}
  label: object
  linestyle or ls: {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
  linewidth or lw: float or None
  path_effects: `.AbstractPathEffect`
  picker: None or bool or float or callable
  rasterized: bool or None
  sketch_params: (scale: float, length: float, randomness: float)
  snap: bool or None
  transform: `.Transform`
  url: str
  visible: bool
  zorder: float
do_3d_projection(self, renderer=None)
# Fix for change in matplotlib 3.5.0 (https://github.com/matplotlib/matplotlib/issues/21688)
draw(self, renderer)
Draw the :class:`Patch` to the given *renderer*.

Methods inherited from matplotlib.patches.FancyArrowPatch:
__str__(self)
Return str(self).
get_arrowstyle(self)
Return the arrowstyle object.
get_connectionstyle(self)
Return the :class:`ConnectionStyle` instance.
get_dpi_cor(self)
dpi_cor is currently used for linewidth-related things and
shrink factor. Mutation scale is affected by this.
 
Returns
-------
dpi_cor : scalar
get_mutation_aspect(self)
Return the aspect ratio of the bbox mutation.
get_mutation_scale(self)
Return the mutation scale.
 
Returns
-------
scale : scalar
get_path(self)
Return the path of the arrow in the data coordinates. Use
get_path_in_displaycoord() method to retrieve the arrow path
in display coordinates.
get_path_in_displaycoord(self)
Return the mutated path of the arrow in display coordinates.
set_arrowstyle(self, arrowstyle=None, **kw)
Set the arrow style. Old attributes are forgotten. Without arguments
(or with ``arrowstyle=None``) returns available box styles as a list of
strings.
 
Parameters
----------
arrowstyle : None, ArrowStyle, str, optional (default: None)
    Can be a string with arrowstyle name with optional comma-separated
    attributes, e.g.::
 
        set_arrowstyle("Fancy,head_length=0.2")
 
    Alternatively attributes can be provided as keywords, e.g.::
 
        set_arrowstyle("fancy", head_length=0.2)
set_connectionstyle(self, connectionstyle, **kw)
Set the connection style. Old attributes are forgotten.
 
Parameters
----------
connectionstyle : None, ConnectionStyle instance, or string
    Can be a string with connectionstyle name with
    optional comma-separated attributes, e.g.::
 
        set_connectionstyle("arc,angleA=0,armA=30,rad=10")
 
    Alternatively, the attributes can be provided as keywords, e.g.::
 
        set_connectionstyle("arc", angleA=0,armA=30,rad=10)
 
    Without any arguments (or with ``connectionstyle=None``), return
    available styles as a list of strings.
set_dpi_cor(self, dpi_cor)
dpi_cor is currently used for linewidth-related things and
shrink factor. Mutation scale is affected by this.
 
Parameters
----------
dpi_cor : scalar
set_mutation_aspect(self, aspect)
Set the aspect ratio of the bbox mutation.
 
Parameters
----------
aspect : scalar
set_mutation_scale(self, scale)
Set the mutation scale.
 
Parameters
----------
scale : scalar
set_patchA(self, patchA)
Set the tail patch.
 
Parameters
----------
patchA : Patch
    :class:`matplotlib.patch.Patch` instance.
set_patchB(self, patchB)
Set the head patch.
 
Parameters
----------
patchB : Patch
    :class:`matplotlib.patch.Patch` instance.
set_positions(self, posA, posB)
Set the begin and end positions of the connecting path.
 
Parameters
----------
posA, posB : None, tuple
    (x,y) coordinates of arrow tail and arrow head respectively. If
    `None` use current value.

Methods inherited from matplotlib.patches.Patch:
contains(self, mouseevent, radius=None)
Test whether the mouse event occurred in the patch.
 
Returns
-------
(bool, empty dict)
contains_point(self, point, radius=None)
Returns ``True`` if the given *point* is inside the path
(transformed with its transform attribute).
 
*radius* allows the path to be made slightly larger or smaller.
contains_points(self, points, radius=None)
Returns a bool array which is ``True`` if the (closed) path
contains the corresponding point.
(transformed with its transform attribute).
 
*points* must be Nx2 array.
*radius* allows the path to be made slightly larger or smaller.
get_aa(self)
Alias for `get_antialiased`.
get_antialiased(self)
Returns True if the :class:`Patch` is to be drawn with antialiasing.
get_capstyle(self)
Return the current capstyle
get_data_transform(self)
Return the :class:`~matplotlib.transforms.Transform` instance which
maps data coordinates to physical coordinates.
get_ec(self)
Alias for `get_edgecolor`.
get_edgecolor(self)
Return the edge color of the :class:`Patch`.
get_extents(self)
Return a :class:`~matplotlib.transforms.Bbox` object defining
the axis-aligned extents of the :class:`Patch`.
get_facecolor(self)
Return the face color of the :class:`Patch`.
get_fc(self)
Alias for `get_facecolor`.
get_fill(self)
return whether fill is set
get_hatch(self)
Return the current hatching pattern
get_joinstyle(self)
Return the current joinstyle
get_linestyle(self)
Return the linestyle.
get_linewidth(self)
Return the line width in points.
get_ls(self)
Alias for `get_linestyle`.
get_lw(self)
Alias for `get_linewidth`.
get_patch_transform(self)
Return the :class:`~matplotlib.transforms.Transform` instance which
takes 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.
get_transform(self)
Return the :class:`~matplotlib.transforms.Transform` applied
to the :class:`Patch`.
get_verts(self)
Return a copy of the vertices used in this patch
 
If the patch contains Bezier curves, the curves will be
interpolated by line segments.  To access the curves as
curves, use :meth:`get_path`.
get_window_extent(self, renderer=None)
Get the axes 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.
set_aa(self, aa)
Alias for `set_antialiased`.
set_alpha(self, alpha)
Set the alpha transparency of the patch.
 
Parameters
----------
alpha : float or None
set_antialiased(self, aa)
Set whether to use antialiased rendering.
 
Parameters
----------
b : bool or None
set_capstyle(self, s)
Set the patch capstyle
 
Parameters
----------
s : {'butt', 'round', 'projecting'}
set_color(self, c)
Set both the edgecolor and the facecolor.
 
Parameters
----------
c : color
 
See Also
--------
Patch.set_facecolor, Patch.set_edgecolor
    For setting the edge or face color individually.
set_ec(self, color)
Alias for `set_edgecolor`.
set_edgecolor(self, color)
Set the patch edge color.
 
Parameters
----------
color : color or None or 'auto'
set_facecolor(self, color)
Set the patch face color.
 
Parameters
----------
color : color or None
set_fc(self, color)
Alias for `set_facecolor`.
set_fill(self, b)
Set whether to fill the patch.
 
Parameters
----------
b : bool
set_hatch(self, hatch)
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.
 
Hatching is supported in the PostScript, PDF, SVG and Agg
backends only.
 
Parameters
----------
hatch : {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
set_joinstyle(self, s)
Set the patch joinstyle
 
Parameters
----------
s : {'miter', 'round', 'bevel'}
set_linestyle(self, ls)
Set the patch linestyle.
 
===========================   =================
linestyle                     description
===========================   =================
``'-'`` or ``'solid'``        solid line
``'--'`` or  ``'dashed'``     dashed line
``'-.'`` or  ``'dashdot'``    dash-dotted line
``':'`` or ``'dotted'``       dotted line
===========================   =================
 
Alternatively a dash tuple of the following form can be provided::
 
    (offset, onoffseq),
 
where ``onoffseq`` is an even length tuple of on and off ink in points.
 
Parameters
----------
ls : {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
    The line style.
set_linewidth(self, w)
Set the patch linewidth in points.
 
Parameters
----------
w : float or None
set_ls(self, ls)
Alias for `set_linestyle`.
set_lw(self, w)
Alias for `set_linewidth`.
update_from(self, other)
Updates this :class:`Patch` from the properties of *other*.

Data descriptors inherited from matplotlib.patches.Patch:
fill
return whether fill is set

Data and other attributes inherited from matplotlib.patches.Patch:
validCap = ('butt', 'round', 'projecting')
validJoin = ('miter', 'round', 'bevel')
zorder = 1

Methods inherited from matplotlib.artist.Artist:
__getstate__(self)
add_callback(self, func)
Add a callback function that will be called whenever one of the
`.Artist`'s properties changes.
 
Parameters
----------
func : callable
    The callback function. It must have the signature::
 
        def func(artist: Artist) -> Any
 
    where *artist* is the calling `.Artist`. Return values may exist
    but are ignored.
 
Returns
-------
oid : int
    The observer id associated with the callback. This id can be
    used for removing the callback with `.remove_callback` later.
 
See Also
--------
remove_callback
convert_xunits(self, x)
Convert *x* using the unit type of the xaxis.
 
If the artist is not in contained in an Axes or if the xaxis does not
have units, *x* itself is returned.
convert_yunits(self, y)
Convert *y* using the unit type of the yaxis.
 
If the artist is not in contained in an Axes or if the yaxis does not
have units, *y* itself is returned.
findobj(self, match=None, include_self=True)
Find artist objects.
 
Recursively find all `.Artist` instances contained in the artist.
 
Parameters
----------
match
    A filter criterion for the matches. This can be
 
    - *None*: Return all objects contained in artist.
    - A function with signature ``def match(artist: Artist) -> bool``.
      The result will only contain artists for which the function
      returns *True*.
    - A class instance: e.g., `.Line2D`. The result will only contain
      artists of this class or its subclasses (``isinstance`` check).
 
include_self : bool
    Include *self* in the list to be checked for a match.
 
Returns
-------
artists : list of `.Artist`
format_cursor_data(self, data)
Return a string representation of *data*.
 
.. note::
    This method is intended to be overridden by artist subclasses.
    As an end-user of Matplotlib you will most likely not call this
    method yourself.
 
The default implementation converts ints and floats and arrays of ints
and floats into a comma-separated string enclosed in square brackets.
 
See Also
--------
get_cursor_data
get_agg_filter(self)
Return filter function to be used for agg filter.
get_alpha(self)
Return the alpha value used for blending - not supported on all
backends
get_animated(self)
Return the animated state.
get_children(self)
Return a list of the child `.Artist`\s of this `.Artist`.
get_clip_box(self)
Return the clipbox.
get_clip_on(self)
Return whether the artist uses clipping.
get_clip_path(self)
Return the clip path.
get_contains(self)
Return the custom contains function of the artist if set, or *None*.
 
See Also
--------
set_contains
get_cursor_data(self, event)
Return the cursor data for a given event.
 
.. note::
    This method is intended to be overridden by artist subclasses.
    As an end-user of Matplotlib you will most likely not call this
    method yourself.
 
Cursor data can be used by Artists to provide additional context
information for a given event. The default implementation just returns
*None*.
 
Subclasses can override the method and return arbitrary data. However,
when doing so, they must ensure that `.format_cursor_data` can convert
the data to a string representation.
 
The only current use case is displaying the z-value of an `.AxesImage`
in the status bar of a plot window, while moving the mouse.
 
Parameters
----------
event : `matplotlib.backend_bases.MouseEvent`
 
See Also
--------
format_cursor_data
get_figure(self)
Return the `.Figure` instance the artist belongs to.
get_gid(self)
Return the group id.
get_in_layout(self)
Return boolean flag, ``True`` if artist is included in layout
calculations.
 
E.g. :doc:`/tutorials/intermediate/constrainedlayout_guide`,
`.Figure.tight_layout()`, and
``fig.savefig(fname, bbox_inches='tight')``.
get_label(self)
Return the label used for this artist in the legend.
get_path_effects(self)
get_picker(self)
Return the picking behavior of the artist.
 
The possible values are described in `.set_picker`.
 
See Also
--------
set_picker, pickable, pick
get_rasterized(self)
Return whether the artist is to be rasterized.
get_sketch_params(self)
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.
 
    Returns *None* if no sketch parameters were set.
get_snap(self)
Returns the snap setting.
 
See `.set_snap` for details.
get_tightbbox(self, renderer)
Like `Artist.get_window_extent`, but includes any clipping.
 
Parameters
----------
renderer : `.RendererBase` instance
    renderer that will be used to draw the figures (i.e.
    ``fig.canvas.get_renderer()``)
 
Returns
-------
bbox : `.BBox`
    The enclosing bounding box (in figure pixel co-ordinates).
get_transformed_clip_path_and_affine(self)
Return the clip path with the non-affine part of its
transformation applied, and the remaining affine part of its
transformation.
get_url(self)
Return the url.
get_visible(self)
Return the visibility.
get_zorder(self)
Return the artist's zorder.
have_units(self)
Return *True* if units are set on the *x* or *y* axes.
is_transform_set(self)
Return whether the Artist has an explicitly set transform.
 
This is *True* after `.set_transform` has been called.
pchanged(self)
Call all of the registered callbacks.
 
This function is triggered internally when a property is changed.
 
See Also
--------
add_callback
remove_callback
pick(self, mouseevent)
Process a pick event.
 
Each child artist will fire a pick event if *mouseevent* is over
the artist and the artist has picker set.
 
See Also
--------
set_picker, get_picker, pickable
pickable(self)
Return whether the artist is pickable.
 
See Also
--------
set_picker, get_picker, pick
properties(self)
Return a dictionary of all the properties of the artist.
remove(self)
Remove the artist from the figure if possible.
 
The effect will not be visible until the figure is redrawn, e.g.,
with `.FigureCanvasBase.draw_idle`.  Call `~.axes.Axes.relim` to
update the axes limits if desired.
 
Note: `~.axes.Axes.relim` will not see collections even if the
collection was added to the axes with *autolim* = True.
 
Note: there is no support for removing the artist's legend entry.
remove_callback(self, oid)
Remove a callback based on its observer id.
 
See Also
--------
add_callback
set(self, **kwargs)
A property batch setter.  Pass *kwargs* to set properties.
set_agg_filter(self, filter_func)
Set the agg filter.
 
Parameters
----------
filter_func : callable
    A filter function, which takes a (m, n, 3) float array and a dpi
    value, and returns a (m, n, 3) array.
 
    .. ACCEPTS: a filter function, which takes a (m, n, 3) float array
        and a dpi value, and returns a (m, n, 3) array
set_animated(self, b)
Set the artist's animation state.
 
Parameters
----------
b : bool
set_clip_box(self, clipbox)
Set the artist's clip `.Bbox`.
 
Parameters
----------
clipbox : `.Bbox`
set_clip_on(self, b)
Set whether the artist uses clipping.
 
When False artists will be visible out side of the axes which
can lead to unexpected results.
 
Parameters
----------
b : bool
set_clip_path(self, path, transform=None)
Set the artist's clip path, which may be:
 
- a :class:`~matplotlib.patches.Patch` (or subclass) instance; or
- a :class:`~matplotlib.path.Path` instance, in which case a
  :class:`~matplotlib.transforms.Transform` instance, which will be
  applied to the path before using it for clipping, must be provided;
  or
- ``None``, to remove a previously set 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: [(`~matplotlib.path.Path`, `.Transform`) | `.Patch` | None]
set_contains(self, picker)
Define a custom contains test for the artist.
 
The provided callable replaces the default `.contains` method
of the artist.
 
Parameters
----------
picker : callable
    A custom picker function to evaluate if an event is within the
    artist. The function must have the signature::
 
        def contains(artist: Artist, event: MouseEvent) -> bool, dict
 
    that returns:
 
    - a bool indicating if the event is within the artist
    - a dict of additional information. The dict should at least
      return the same information as the default ``contains()``
      implementation of the respective artist, but may provide
      additional information.
set_figure(self, fig)
Set the `.Figure` instance the artist belongs to.
 
Parameters
----------
fig : `.Figure`
set_gid(self, gid)
Set the (group) id for the artist.
 
Parameters
----------
gid : str
set_in_layout(self, in_layout)
Set if artist is to be included in layout calculations,
E.g. :doc:`/tutorials/intermediate/constrainedlayout_guide`,
`.Figure.tight_layout()`, and
``fig.savefig(fname, bbox_inches='tight')``.
 
Parameters
----------
in_layout : bool
set_label(self, s)
Set a label that will be displayed in the legend.
 
Parameters
----------
s : object
    *s* will be converted to a string by calling `str`.
set_path_effects(self, path_effects)
Set the path effects.
 
Parameters
----------
path_effects : `.AbstractPathEffect`
set_picker(self, picker)
Define the picking behavior of the artist.
 
Parameters
----------
picker : None or bool or float or callable
    This 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.
set_rasterized(self, rasterized)
Force rasterized (bitmap) drawing in vector backend output.
 
Defaults to None, which implies the backend's default behavior.
 
Parameters
----------
rasterized : bool or None
set_sketch_params(self, scale=None, length=None, randomness=None)
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)
 
    .. ACCEPTS: (scale: float, length: float, randomness: float)
set_snap(self, snap)
Set the snapping behavior.
 
Snapping aligns positions with the pixel grid, which results in
clearer images. For example, if a black line of 1px width was
defined at a position in between two pixels, the resulting image
would contain the interpolated value of that line in the pixel grid,
which would be a grey value on both adjacent pixel positions. In
contrast, snapping will move the line to the nearest integer pixel
value, so that the resulting image will really contain a 1px wide
black line.
 
Snapping is currently only supported by the Agg and MacOSX backends.
 
Parameters
----------
snap : bool or None
    Possible values:
 
    - *True*: Snap vertices to the nearest pixel center.
    - *False*: Do not modify vertex positions.
    - *None*: (auto) If the path contains only rectilinear line
      segments, round to the nearest pixel center.
set_transform(self, t)
Set the artist transform.
 
Parameters
----------
t : `.Transform`
set_url(self, url)
Set the url for the artist.
 
Parameters
----------
url : str
set_visible(self, b)
Set the artist's visibility.
 
Parameters
----------
b : bool
set_zorder(self, level)
Set the zorder for the artist.  Artists with lower zorder
values are drawn first.
 
Parameters
----------
level : float
update(self, props)
Update this artist's properties from the dictionary *props*.

Data descriptors inherited from matplotlib.artist.Artist:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)
aname
axes
The `~.axes.Axes` instance the artist resides in, or *None*.
mouseover
stale
Whether the artist is 'stale' and needs to be re-drawn for the output
to match the internal state of the artist.
sticky_edges
``x`` and ``y`` sticky edge lists for autoscaling.
 
When performing autoscaling, if a data limit coincides with a value in
the corresponding sticky_edges list, then no margin will be added--the
view limit "sticks" to the edge. A typical use case is histograms,
where one usually expects no margin on the bottom edge (0) of the
histogram.
 
This attribute cannot be assigned to; however, the ``x`` and ``y``
lists can be modified in place as needed.
 
Examples
--------
 
>>> artist.sticky_edges.x[:] = (xmin, xmax)
>>> artist.sticky_edges.y[:] = (ymin, ymax)

 
Functions
       
UV_arrows(UV, alabel='a', blabel='b', clabel='c')
Plot arrows with a*,b* on current figure
axis_lattice_points(vec_a=[1, 0, 0], vec_b=[0, 1, 0], axis=[-4, 4, -4, 4])
Generate a 2D lattice of points generated by 2 vectors within a 2D axis
:param vec_a: [1x3] array : a* vector
:param vec_b: [1x3] array : b* vector
:param axis: [1x4] axis array, plt.axis()
:return: [nx3] array of lattice points
labels(ttl=None, xvar=None, yvar=None, zvar=None, legend=False, size='Normal', font='Times New Roman')
Add formatted labels to current plot, also increases the tick size
:param ttl: title
:param xvar: x label
:param yvar: y label
:param zvar: z label (3D plots only)
:param legend: False/ True, adds default legend to plot 
:param size: 'Normal' or 'Big'
:param font: str font name, 'Times New Roman'
:return: None
multiplot(xvals, yvals=None, datarange=None, cmap='jet', labels=None, marker=None)
Shortcut to creating a simple multiplot with either colorbar or legend
E.G.
  x = np.arange(-5,5,0.1)
  ys = [x**2, 1+x**2, 2+x**2, 3+x**2, 4+x**2]
  datarange = [0,1,2,3,4]
  multiplot(x, ys, datarange, cmap='winter')
OR:
  x = np.arange(-5,5,0.1)
  ys = [x**2, 1+x**2, 2+x**2, 3+x**2, 4+x**2]
  labels = ['x*x','2+x*x','3+x*x','4+x*x']
  multiplot(x, ys, labels=labels)
newplot(*args, **kwargs)
Shortcut to creating a simple plot
E.G.
  x = np.arange(-5,5,0.1)
  y = x**2
  newplot(x,y,'r-',lw=2,label='Line')
newplot3(*args, **kwargs)
Shortcut to creating a simple 3D plot
Automatically tiles 1 dimensional x and y arrays to match 2D z array,
assuming z.shape = (len(x),len(y))
  newplot3(x, y, z, ...)
 
E.G.
  newplot3([1,2,3,4],[9,8,7],[[2,4,6],[8,10,12],[14,16,18],[20,22,24]],'-o')
plot3darray(vec, *args, **kwargs)
Plot 3D vectors in 3D
    plt.plot(vec[:, 0], vec[:, 1], vec[:, 3], *args, **kwargs)
:param vec: [n*3] array
:param args: args to pass to plt.plot
:param kwargs: kwargs to pass to plt.plot
:return: matplotlib plot object
plot_arrow(x, y, z=None, col='r', width=2, arrow_size=40)
Plot arrow in 2D or 3D on current axes
Usage 2D:
  plot_arrow([xi,xf],[yi,yf])
Usage 3D:
  plot_arrow([xi,xf],[yi,yf],[zi,zf])
 
Options:
  width = line width (Def. = 2)
  arrow_size = size of arrow head (Def. = 40)
  col = arrow color (Deg. = red)
plot_atomic_scattering_factor(element, min_energy=0.5, max_energy=20)
Plot atomic scattering factor for 1 or more elements
:param element: str name of element to plot
:param min_energy: float min energy in keV
:param max_energy: float max energy in keV
:return: None
plot_cell(cell_centre=[0, 0, 0], CELL=array([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]]), color='k')
Plot a box defined by a unit cell on the current plot
:param cell_centre: [1x3] array : centre of cell, default [0,0,0]
:param CELL: [3x3] array : unit cell vectors [A,B,C]
:return: None
plot_circle(radius=1.0, centre=[0, 0], height=0, *args, **kwargs)
Generate circle on current plot
:param radius: radius of the circle
:param centre: [x,y] centre of the circle
:param height: reduce the radius by increasing the height from a surface
:param args: plot commands
:param kwargs: plot commands
:return: none
plot_diffractometer_reciprocal_space(phi, chi, eta, mu, delta, gamma, uv, u, lab, energy_kev)
Plot crystal axes in lab frame of 6-circle diffractometer
:param phi:
:param chi:
:param eta:
:param mu:
:param delta:
:param gamma:
:param uv:
:param u:
:param lab:
:param energy_kev:
:return:
plot_ewald_coverage(energy_kev, color='k', linewidth=2)
Plot Ewald coverage of a single axis diffractometer on current plot in 2D
Includes boundaries for theta=0, twotheta=180 and theta=twotheta
 
:param energy_kev: float
:param color: str
:param linewidth: float
:return: None
plot_lattice_lines(latt, vec_a=(1, 0, 0), vec_b=(0, 1, 0), axis=None, *args, **kwargs)
Add lines defining the reciprocal lattice to the current plot
    Generates square or hexagonal lines where vertices are the lattice points within the image.
:param latt: [nx2/3] array : points at which to generate lattice
:param vec_a: [1x2/3] array : a* vector
:param vec_b: [1x2/3] array : b* vector
:param axis: axis to plot on (None for plt.gca)
:param args: argments to pass to plot function, e.g. linewidth, alpha, color
:return: None
plot_lattice_points2D(Q, markersize=12, color='b', marker='o')
Add points to the current axis
:param Q: [nx2/3] array : lattice points to plot
:param markersize: default 12
:param color: default 'b'
:param marker: default 'o'
:return: None
plot_lattice_points3D(Q, point_size=None, color=None, cmap=None)
Plot lattice points is 3D reciprocal space
:param Q: [nx3] array of wavevector transfer positions in reciprocal space, units A^-1
:param point_size: scalar or array of length n, determines each point size (for intensity), in pixels
:param color: colour specifier, can be a list of values length n
:param cmap: str name of colormap to use if color is a list of values
:return:
plot_magnetic_form_factor(elements, maxq=10)
Plot magnetic form factor for 1 or more elements
:param elements:
:return: None
plot_vector_arrows(vec_a=[1, 0, 0], vec_b=[1, 0, 0], vec_a_lab=None, vec_b_lab=None, arrow_size=40, color='b', fontsize=18, axis=None)
Plot vector arrows for Cell on current axis
    Will generate two arrows on the current axis, pointing from the origin to vec_a and vec_b, respectivley.
:param vec_a: [1x2/3] array : a* vector
:param vec_b: [1x2/3] array : b* vector
:param vec_a_lab: str : e.g. 'a*'
:param vec_b_lab: str : e.g. 'b*'
:param arrow_size: size of arrow, default 40
:param color:  arror colour, default 'b'
:param fontsize: text size, default 18
:return: None
plot_xray_attenuation(elements, min_energy=0, max_energy=20)
Plot x-ray scattering factor for 1 or more elements
:param elements:
:return: None
plot_xray_attenuation_length(chemical_formula, density=8.9, energy_range=None, grazing_angle=90)
Plot the X-Ray Attenuation Length of a compound
Equivalent to: https://henke.lbl.gov/optical_constants/atten2.html
Based on formulas from: Henke, Gullikson, and Davis, Atomic Data and Nuclear Data Tables 54 no.2, 181-342 (July 1993)
:param chemical_formula: str molecular formula
:param density: float density in g/cm^3
:param energy_range: array x-ray energy in keV, None for default range
:param grazing_angle: incidence angle relative to the surface, in degrees
:return: float or array, in microns
plot_xray_reflectivity(chemical_formula, density=8.9, energy_range=None, grazing_angle=2)
Plot the specular reflectivity of a material
From: https://xdb.lbl.gov/Section4/Sec_4-2.html
:param chemical_formula: str molecular formula
:param density: float, density in g/cm^3
:param energy_range: float or array, x-ray energy in keV
:param grazing_angle: float, incidence angle relative to the surface, in degrees
:return: None
plot_xray_refractive_index(chemical_formula, density=8.9, energy_range=None)
Plot the Complex Index of Refraction of a compound
    n = 1 - (1/2pi)N*r0*lambda^2*(f1+if2) = 1 - Delta - iBeta
Equivalent to: https://henke.lbl.gov/optical_constants/getdb2.html
Based on formulas from: Henke, Gullikson, and Davis, Atomic Data and Nuclear Data Tables 54 no.2, 181-342 (July 1993)
:param chemical_formula: str molecular formula
:param density: float density in g/cm^3
:param energy_range: array x-ray energy in keV, None for default range
:return: float or array, in microns
plot_xray_scattering_factor(elements, maxq=10)
Plot x-ray scattering factor for 1 or more elements
:param elements:
:return: None
plot_xray_transmission(chemical_formula, density=8.9, energy_range=None, thickness_um=100)
Plot transmission of x-ray through a slab of material at range of energies
Equivalent to https://henke.lbl.gov/optical_constants/filter2.html
Based on formulas from: Henke, Gullikson, and Davis, Atomic Data and Nuclear Data Tables 54 no.2, 181-342 (July 1993)
:param chemical_formula: str molecular formula
:param density: float density in g/cm^3
:param energy_range: array x-ray energy in keV, None for default range
:param thickness_um: slab thickness in microns
:return: float or array
saveplot(name, dpi=None, figure=None)
Saves current figure as a png in the home directory
:param name: filename, including or expluding directory and or extension
:param dpi: image resolution, higher means larger image size, default=matplotlib default
:param figure: figure number, default = plt.gcf()
:return: None
 
E.G.
---select figure to save by clicking on it---
saveplot('test')
E.G.
saveplot('c:\somedirpicture.jpg', dpi=600, figure=3)
set_plot_defaults(rcdefaults=False)
Set custom matplotlib rcparams, or revert to matplotlib defaults
These handle the default look of matplotlib plots
See: https://matplotlib.org/stable/tutorials/introductory/customizing.html#the-default-matplotlibrc-file
:param rcdefaults: False*/ True, if True, revert to matplotlib defaults
:return: None
sliderplot(YY, X=None, slidervals=None, *args, **kwargs)
Shortcut to creating a simple 2D plot with a slider to go through a third dimension
YY = [nxm]: y axis data (initially plots Y[0,:])
 X = [n] or [nxm]:  x axis data (can be 1D or 2D, either same length or shape as Y)
 slidervals = None or [m]: Values to give in the slider
 
E.G.
  sliderplot([1,2,3],[[2,4,6],[8,10,12],[14,16,18],[20,22,24]],slidervals=[3,6,9,12])
sliderplot2D(ZZZ, XX=None, YY=None, slidervals=None, *args, **kwargs)
Shortcut to creating an image plot with a slider to go through a third dimension
ZZZ = [nxmxo]: z axis data
 XX = [nxm] or [n]:  x axis data
 YY = [nxm] or [m]: y axis data
 slidervals = None or [o]: Values to give in the slider
 
if XX and/or YY have a single dimension, the 2D values are generated via meshgrid
 
E.G.
  sliderplot([1,2,3],[[2,4,6],[8,10,12],[14,16,18],[20,22,24]],slidervals=[3,6,9,12])
vecplot(UV, mode='hk0', axis=None, *args, **kwargs)
Plot grid of a,b vectors on current axis
:param UV: [a;b;c] array of unit vectors
:param mode: definition of axis plane, 'hk0', 'h0l', '0kl', 'hhl'
:param axis: axis to create lines on, if None, plt.gca is used
:param args: arguments to pass to plot command, e.g. linewidth, alpha, color
:return: None

 
Data
        DEFAULT_FONT = 'Times New Roman'
DEFAULT_FONTSIZE = 14
FIGURE_DPI = 80
FIGURE_SIZE = [12, 8]