XarrayImage
- class PlasmaCalcs.plotting.images.XarrayImage(array, t=None, *, x=None, y=None, ax=None, image_mode='pcolormesh', init_plot=True, add_colorbar=UNSET, add_labels=True, title=UNSET, **kw_super)
Bases:
MoviePlotNode,PlotDimsMixinMoviePlotNode of an xarray.DataArray.
stores an XarrayImagePlotElement & has methods for plotting & updating the image!“image” refers to a matplotlib.cm.ScalarMappable object, e.g. the result of imshow or pcolormesh.- array: xarray.DataArray, probably ndim=3; or xarray.Dataset with single data_var
- the data to be plotted. if ndim=2, can still plot, but nothing to animate.if xarray.Dataset, must have only one data_var; will create image of that data_var.
- t: None or str
- the array dimension which frames will index. E.g. ‘time’.None -> infer from array & any other provided dimensions.if provided but dimension not found, attempt xarray_promote_dim before crashing.
- x, y: None or str
- if provided, tells dimensions for the x, y plot axes.None -> infer from array & any other provided dimensions.if provided but dimension not found, attempt xarray_promote_dim before crashing.
- ax: None or Axes
- the attached mpl.axes.Axes object.None –> will use self.ax=plt.gca() when getting self.ax for the first time.
- image_mode: str (‘imshow’ or ‘pcolormesh’) (default: pcolormesh)
- tells whether this image will be pcolormesh or imshow.
- init_plot: bool (default: True)
- whether to call self.init_plot() immediately, during __init__.(as a PlotSetting: tells the value of init_plot passed during __init__.)False –> still must call self.init_plot() before using self(…) or self.updater(…)(end-user will probably never use init_plot=False; it’s mostly for internal code.)(might use False if creating MovieImage before defining the associated Axes.)
- xmargin, ymargin, margin: None or number (greater than -0.5, probably close to 0.05) (default: None)
- margin to use for x/y axis, as a fraction of the data interval for that axis.None –> use matplotlib defaults(e.g., plt.rcParams[“axes.xmargin”] or [“axes.ymargin”], or 0 if using imshow)positive number –> pad around the data region, with this much whitespace.E.g. 0.05 means adding 5% whitespace on each side.Use this to zoom out.negative number –> remove this much of the outer parts of the data region.E.g. -0.2 means removing 20% space from each side.Use this to zoom in.For line plots, if also using
robust, ymargin will be applied to the robust y lims.(margin-related params share the same docstring, but refer to:‘xmargin’: x-axis, ‘ymargin’: y-axis, ‘margin’: x and/or y-axis.) - title: UNSET, None, or str (default: UNSET)
- title for a single axes/subplot. For xarrays, will title.format(**xarray_nondim_coords(array)).(Note: plot_settings[‘title’] should always be the ‘base’ title, before title.format(…))UNSET –> use array_at_current_frame._title_for_slice() if XarrayImage (or other single-array plot).use XarraySubplotTitlesInferer.infer_title() if XarraySubplots (or other multi-array plot).None –> do not add a title.
- title_font: UNSET, None, or str (default: UNSET)
- font for title, e.g. ‘serif’, ‘sans-serif’, or ‘monospace’UNSET –> use DEFAULTS.PLOT.MOVIE_TITLE_FONT (default: monospace).None –> use matplotlib default.
- title_y: UNSET, None, or number (default: UNSET)
- y position for title, in axes coordinates.
- title_kw: UNSET, or dict (default: UNSET)
- any additional kwargs for plt.title.
- grid: UNSET, bool, or dict (default: UNSET)
- whether to ax.grid() for each axes.UNSET –> use rcParams[“axes.grid”].True –> ax.grid(True) for all axes.False –> ax.grid(False) for all axes.dict –> ax.grid(**grid) for all axes.
# [TODO] exampleTo view or adjust plot settings in self, see self.plot_settings, or help(self.plot_settings).Methods
__call__(frame)update the plot for the given frame.
__getitem__(i)returns self.children[i].
__init_subclass__(*args_super, **kw)appends note about using self.plot_settings, to cls.__doc__.
__iter__()iterates over self.children.
add_child(child)adds this child (a Tree) to self.children.
display([show_depth, max_depth, shorthand])display self in html.
enumerate_flat(*[, include_self])returns a generator which iterates over all of self's descendants, in depth-first order,
flat(*[, include_self])returns a generator which iterates over all of self's descendants, in depth-first order.
flat_branches_until(branches_until, *[, ...])returns a generator which iterates over all of self's descendants, in depth-first order,
get_animator(*[, fps, blit, frames, plt_close])returns FuncAnimation instance using self as func.
get_data_at_frame(frame)returns {'array': array at this frame}, properly transposed & ready for plotting.
return max of get_nframes_here() for self & all descendants of self.
return the number of frames that could be in the movie, based on this node.
help()prints a helpful message with examples for how to use this cls
html([show_depth, max_depth, shorthand])returns html for displaying self and all of self's children.
infer_xyt_dims(*[, xy_fail_ok, t_fail_ok])infers (x,y,t) dims from self.x, y, dim.
plot for the first time.
init_plots(*[, plotted_ok])init_plot for self & all descendants with non-None obj.
make_child(obj)makes a child of self, with obj as its stored object, and returns the child.
make_children(objs)make_child(obj) for obj in objs; returns the list of newly made children.
adds title (as a MovieTextNode) on self.ax.
save(filename[, frames, fps, blit])save the movie to filename.
scatter_max(**kw_scatter)use XarrayScatter to plt.scatter() a single marker, at the argmax of self.array.
scatter_min(**kw_scatter)use XarrayScatter to plt.scatter() a single marker, at the argmin of self.array.
scatter_where(condition, **kw_scatter)use XarrayScatter to plt.scatter() markers where condition is True.
set_parent(parent, *[, _internal])sets self.parent = parent.
update_to_frame(frame)update the plot for the given frame.
tells whether self.array is not 2D
_get_frames(value)gets frames based on value and possibly self.get_nframes() if necessary.
_get_plot_dims_attr_value(x[, default])get value of self.{plot_dims_attrs[x]}, where x = 'x', 'y', 't', 'dims', or 't_necessary_if'.
return whether this array is plottable, i.e. all plot_dims can be inferred,.
checks to run before init_plot().
_on_added_child(child)called immediately after adding a child to self.
_on_added_descendant(descendant)called immediately after adding a descendant to self (or any of self.children).
_on_adding_ancestor(ancestor)called immediately before adding an ancestor to self (i.e., self.parent, parent of self.parent, etc)
_on_setting_parent(parent)called immediately before setting self.parent = parent.
returns html string for displaying self.
_set_plot_dims_attr_value(x, value)set value of self.{plot_dims_attrs[x]}, where x = 'x', 'y', 't', 'dims', or 't_necessary_if'.
returns shorthand repr for this node (without children): "((depth, height, size)) obj".
Attributes
DEFAULT_TREE_SHORTHANDDEFAULT_TREE_SHOW_DEPTHDEFAULT_TREE_SHOW_MAX_DEPTHalias to get_animator
mpl.axes.Axes where this XarrayImage is plotted, or None if not plotted.
the mpl.colorbar.Colorbar of this XarrayImage.
number of layers above self.
figure where this XarrayImage is plotted, or None if not plotted.
the currently-plotted frame
the frames that could be in the movie.
number of layers below self.
mpl.cm.ScalarMappable object of this XarrayImage, or None if not plotted.
parent node of self.
stores parent value, but internally uses weakref to avoid circular references.
plot_dims_attrswhether this node's element has actually been plotted yet.
the currently plotted data.
number of nodes in this tree.
the dimension which is actually used to index the movie's frames (i.e. the "time axis").
the dimension which is actually used to index the plot's x axis.
(self.x_plot_dim, self.y_plot_dim)
(self.x_plot_dim, self.y_plot_dim, self.t_plot_dim)
the dimension which is actually used to index the plot's y axis.
- __call__(frame)
update the plot for the given frame. return iterable of all updated artists.
Defining __call__ in this way means self is compatible for direct use by FuncAnimation.
- __getitem__(i)
returns self.children[i]. If i is a tuple, index repeatedly, e.g. self[i[0]][i[1]][i[2]]…
- classmethod __init_subclass__(*args_super, **kw)
appends note about using self.plot_settings, to cls.__doc__.
if “PlotSettings” or “plot_settings” appears in cls.__doc__, do NOT append this note;assuming instead that this means the doc already mentions how to use plot_settings.
- __iter__()
iterates over self.children.
- _array_is_not_2D()
tells whether self.array is not 2D
- _get_frames(value)
gets frames based on value and possibly self.get_nframes() if necessary.
if result would be None, crash instead.
- _get_plot_dims_attr_value(x, default=NO_VALUE)
get value of self.{plot_dims_attrs[x]}, where x = ‘x’, ‘y’, ‘t’, ‘dims’, or ‘t_necessary_if’.
- _has_valid_plot_dims()
return whether this array is plottable, i.e. all plot_dims can be inferred,
and array doesn’t have more than 3 dims.
- _init_plot_checks()
checks to run before init_plot().
Here, checks:- if self.plotted, raise PlottingAmbiguityError.- if self.obj is None, raise PlottingAmbiguityError.
- _on_added_child(child)
called immediately after adding a child to self.
Tracks depth, height, size. This method does not connect any parents or children.
- _on_added_descendant(descendant)
called immediately after adding a descendant to self (or any of self.children).
Tracks depth, height, size. This method does not connect any parents or children.
- _on_adding_ancestor(ancestor)
called immediately before adding an ancestor to self (i.e., self.parent, parent of self.parent, etc)
Tracks depth, height, size. This method does not connect any parents or children.
- _on_setting_parent(parent)
called immediately before setting self.parent = parent.
Tracks depth, height, size. This method does not connect any parents or children.
- _repr_html_()
returns html string for displaying self. (this display hook is used by Jupyter automatically.).
Includes self.html() and DEFAULTS.TREE_CSS.
[TODO] apply the css to ONLY this output cell in Jupyter, instead of all output cells…
- _set_plot_dims_attr_value(x, value)
set value of self.{plot_dims_attrs[x]}, where x = ‘x’, ‘y’, ‘t’, ‘dims’, or ‘t_necessary_if’.
- _shorthand_repr()
returns shorthand repr for this node (without children): “((depth, height, size)) obj”.
- add_child(child)
adds this child (a Tree) to self.children. Also, child.set_parent(self).
returns the added child.
- property ani
alias to get_animator
- property ax
mpl.axes.Axes where this XarrayImage is plotted, or None if not plotted.
- property cbar
the mpl.colorbar.Colorbar of this XarrayImage.
None if image not plotted.False if image plotted but does not have an associated colorbar.
- property depth
number of layers above self. (parent, parent’s parents, etc.)
depth = 0 for the node with parent = None.
- display(show_depth=None, max_depth=None, *, shorthand=None)
display self in html. Includes self.html() and DEFAULTS.TREE_CSS.
- show_depth: None or int
- max number of layers of tree to show by default (i.e. “not hidden” by default)None –> use self.DEFAULT_TREE_SHOW_DEPTH if defined else DEFAULTS.TREE_SHOW_DEPTH
- max_depth: None or int
- max number of layers of tree to render (even if all layers are “not hidden”).Anything deeper will not be converted to html string.None –> use self.DEFAULT_TREE_SHOW_MAX_DEPTH if defined else DEFAULTS.TREE_SHOW_MAX_DEPTH
- shorthand: None or bool
- whether to use shorthand for the “Tree([depth=N, height=N, size=N], obj=…)” part of the repr.True –> use shorthand; replace that^ with: “((N, N, N)) …”None –> use self.DEFAULT_TREE_SHORTHAND if defined else DEFAULTS.TREE_SHORTHAND
- element_cls
alias of
XarrayImagePlotElement
- enumerate_flat(*, include_self=False)
returns a generator which iterates over all of self’s descendants, in depth-first order,
yielding (index, node) pairs, such that self[index] == node.Note that index will be a tuple with length == node.depth.if include_self, yield self first, as: ((), self)).
- property fig
figure where this XarrayImage is plotted, or None if not plotted.
- flat(*, include_self=False)
returns a generator which iterates over all of self’s descendants, in depth-first order.
if include_self, yield self first.
- flat_branches_until(branches_until, *, include_self=False)
returns a generator which iterates over all of self’s descendants, in depth-first order,
but stop looking at descendants on a branch as soon as branches_until(node).E.g. self.flat_branches_until(lambda node: node.obj==7) will be similar to flat,but won’t go to any descendants for any node with obj==7.if include self, yield self first, and check branches_until(self) before continuing.otherwise, never check branches_until(self).
- property frame
the currently-plotted frame
- property frames
the frames that could be in the movie.
if set to None, will use self.get_nframes() instead.if set to a slice, will use range(self.get_nframes())[frames] instead.
- get_animator(*, fps=UNSET, blit=UNSET, frames=UNSET, plt_close=True, **kw_func_animation)
returns FuncAnimation instance using self as func.
Use kwarg defaults from self.plot_settings, for any kwargs not provided here.- fps: UNSET, None, or number (default: UNSET)
- frames per second.UNSET –> use DEFAULTS.PLOT.FPS (default: 30).(Or use value from self.plot_settings, if provided.)None –> use matplotlib defaults.
- blit: UNSET, None, or bool (default: UNSET)
- whether to use blitting.UNSET –> use DEFAULTS.PLOT.BLIT (default: True).(Or use value from self.plot_settings, if provided.)if None, use matplotlib defaults.
- frames: UNSET, None, int, iterable, or slice (default: UNSET)
- passed to FuncAnimation. Tells number of frames or which frames to plot.If UNSET, use value from self.plot_settings if possible else getattr(self, ‘frames’, None).if slice, use range(self.get_nframes())[frames], crashing if self doesn’t have ‘get_nframes’.
- plt_close: bool
- whether to plt.close() before returning the result.This is useful in Jupyter, where commonly one cell might make a plot,then call get_animator() to display movie in-line, but not plt.close().In that case, plt_close=False would display animation & plot
[TODO] use init_func kwarg to avoid calling self twice for frame 0?
- get_data_at_frame(frame)
returns {‘array’: array at this frame}, properly transposed & ready for plotting.
- get_nframes()
return max of get_nframes_here() for self & all descendants of self.
If any node throws PlottingNframesUnknownError, pretend they said nframes=0.If all nodes throw PlottingNframesUnknownError, raise the one from self.
- get_nframes_here()
return the number of frames that could be in the movie, based on this node.
- property height
number of layers below self. (children, children’s children, etc.)
height = 0 for a node with no children.
- classmethod help()
prints a helpful message with examples for how to use this cls
- html(show_depth=None, max_depth=None, *, shorthand=None)
returns html for displaying self and all of self’s children.
- show_depth: None or int
- max number of layers of tree to show by default (i.e. “not hidden” by default)None –> use self.DEFAULT_TREE_SHOW_DEPTH if defined else DEFAULTS.TREE_SHOW_DEPTH
- max_depth: None or int
- max number of layers of tree to render (even if all layers are “not hidden”).Anything deeper will not be converted to html string.None –> use self.DEFAULT_TREE_SHOW_MAX_DEPTH if defined else DEFAULTS.TREE_SHOW_MAX_DEPTH
- shorthand: None or bool
- whether to use shorthand for the “Tree([depth=N, height=N, size=N], obj=…)” part of the repr.True –> use shorthand; replace that^ with: “((N, N, N)) …”None –> use self.DEFAULT_TREE_SHORTHAND if defined else DEFAULTS.TREE_SHORTHAND
- property im
mpl.cm.ScalarMappable object of this XarrayImage, or None if not plotted.
- infer_xyt_dims(*, xy_fail_ok=False, t_fail_ok=True)
infers (x,y,t) dims from self.x, y, dim.
- xy_fail_ok, t_fail_ok: bool
- controls behavior when failing to infer a dim:True –> return None for that dimFalse –> raise PlottingAmbiguityErrort_fail_ok corresponds to t; xy_fail_ok corresponds to x,y.
see also: DEFAULTS.PLOT.DIMS_INFER, plotting.infer_xyt_dims, infer_xy_dims, infer_movie_dim
- init_plot()
plot for the first time. Save the XarrayImagePlotElement at self.obj.
- init_plots(*, plotted_ok=True)
init_plot for self & all descendants with non-None obj.
- plotted_ok: bool
- True –> skip node if node.plotted.False –> call init_plot on all nodes with non-None obj.
- make_child(obj)
makes a child of self, with obj as its stored object, and returns the child.
- make_children(objs)
make_child(obj) for obj in objs; returns the list of newly made children.
- property parent
parent node of self. None if self is root.
When set to a value, calls self.set_parent(value),which also updates tracking info appropriately, and updates parent’s children.
- property parent_ref
stores parent value, but internally uses weakref to avoid circular references.
Users should always use self.parent instead.
- plot_title()
adds title (as a MovieTextNode) on self.ax.
raise PlottingAmbiguityError if title already plotted(this prevents having multiple title nodes).
- property plotted
whether this node’s element has actually been plotted yet.
False before init_plot; True after. Always None if self.obj is None.
- property plotted_data
the currently plotted data.
- save(filename, frames=UNSET, *, fps=UNSET, blit=UNSET, **kw)
save the movie to filename.
RECOMMENDED:first, self.save(…, frames=N), with small N (e.g. N=5), to test movie formatting.- Troubleshooting: if movie getting cut off,
- try plt.subplots_adjust(bottom=0.2, left=0.2, right=0.8, top=0.8),or even more extreme values if necessary. (0 is bottom/left edge; 1 is top/right edge.)
- frames: UNSET, None, int, iterable, or slice (default: UNSET)
- passed to FuncAnimation. Tells number of frames or which frames to plot.If UNSET, use value from self.plot_settings if possible else getattr(self, ‘frames’, None).if slice, use range(self.get_nframes())[frames], crashing if self doesn’t have ‘get_nframes’.
- fps: UNSET, None, or number (default: UNSET)
- frames per second.UNSET –> use DEFAULTS.PLOT.FPS (default: 30).(Or use value from self.plot_settings, if provided.)None –> use matplotlib defaults.
- blit: UNSET, None, or bool (default: UNSET)
- whether to use blitting.UNSET –> use DEFAULTS.PLOT.BLIT (default: True).(Or use value from self.plot_settings, if provided.)if None, use matplotlib defaults.
additional kwargs passed to FuncAnimation() or FuncAnimation.save().returns abspath of the saved movie.
- scatter_max(**kw_scatter)
use XarrayScatter to plt.scatter() a single marker, at the argmax of self.array.
animatable (e.g. different max for each frame); does self.add_child(scatter result)default style: {**DEFAULTS.PLOT.SCATTER_STYLE, **DEFAULTS.PLOT.SCATTER_MAX}returns XarrayScatter object (which got added as child of self).see also: xarray_scatter_max (or, array.pc.scatter_max)
- scatter_min(**kw_scatter)
use XarrayScatter to plt.scatter() a single marker, at the argmin of self.array.
animatable (e.g. different min for each frame); does self.add_child(scatter result)default style: {**DEFAULTS.PLOT.SCATTER_STYLE, **DEFAULTS.PLOT.SCATTER_MIN}returns XarrayScatter object (which got added as child of self).see also: xarray_scatter_min (or, array.pc.scatter_min)
- scatter_where(condition, **kw_scatter)
use XarrayScatter to plt.scatter() markers where condition is True.
animatable (e.g. different condition for each frame); does self.add_child(scatter result)returns XarrayScatter object (which got added as child of self).- condition: callable or DataArray of bools
- callable –> use condition(self.array)DataArray –> ignore self.array entirely.
For x, y, t plot dims, uses self.x_plot_dim, self.y_plot_dim, self.t_plot_dim.see also: xarray_scatter_where (or, array.pc.scatter_where)Example:xim = array.pc.image(…)xim.scatter_where(lambda arr: arr > 7.5) # marker at all points where arr > 7.5xim.save(filename) # save animation to filename (if xim.t_plot_dim is not None)
- set_parent(parent, *, _internal=False)
sets self.parent = parent. Also, parent.add_child(self), unless _internal=True.
Users should use self.parent = parent instead of calling set_parent directly.
- property size
number of nodes in this tree. (here and below)
size = 1 for a node with no children.
- property t_plot_dim
the dimension which is actually used to index the movie’s frames (i.e. the “time axis”).
setting self.t_plot_dim=value also sets self.{plot_dims_attrs[‘t’]}=value.getting self.t_plot_dim will get self.{plot_dims_attrs[‘t’]} if it is not None;otherwise, infer from self.{plot_dims_attrs[‘dims’]}, self.{plot_dims_attrs[‘x’]}, and self.{plot_dims_attrs[‘y’]}if self.{plot_dims_attrs[‘t_necessary_if’]}(), result might be None.
- update_to_frame(frame)
update the plot for the given frame. set self.frame=frame.
also calls update_to_frame for all children.return iterable of all updated artists.
- property x_plot_dim
the dimension which is actually used to index the plot’s x axis.
setting self.x_plot_dim=value also sets self.{plot_dims_attrs[‘x’]}=value.getting self.x_plot_dim will get self.{plot_dims_attrs[‘x’]} if it is not None;otherwise, infer from self.{plot_dims_attrs[‘dims’]}, self.{plot_dims_attrs[‘t’]}, and self.{plot_dims_attrs[‘y’]}.
- property xy_plot_dims
(self.x_plot_dim, self.y_plot_dim)
- property xyt_plot_dims
(self.x_plot_dim, self.y_plot_dim, self.t_plot_dim)
- property y_plot_dim
the dimension which is actually used to index the plot’s y axis.
setting self.y_plot_dim=value also sets self.{plot_dims_attrs[‘y’]}=value.getting self.y_plot_dim will get self.{plot_dims_attrs[‘y’]} if it is not None;otherwise, infer from self.{plot_dims_attrs[‘dims’]}, self.{plot_dims_attrs[‘t’]}, and self.{plot_dims_attrs[‘x’]}.