nested_grid_plotter.AnimatedPlotter#
- class nested_grid_plotter.AnimatedPlotter(fig: Figure | None = None, builder: NestedBuilder | None = None)[source]#
Bases:
NestedGridPlotterNestedgrid plotter with embedded animation support.
- __init__(fig: Figure | None = None, builder: NestedBuilder | None = None) None[source]#
Initiate the instance.
- Parameters:
fig_params (Optional[Dict[str, Any]], optional) – See
NestedGridPlotterfor other possible arguments. The default is None.subfigs_params (Optional[Dict[str, Any]], optional) – DESCRIPTION. The default is None.
subplots_mosaic_params (Optional[Dict[str, Any]], optional) – DESCRIPTION. The default is None.
- Return type:
None
Public methods summary
__delattr__(name, /)Implement delattr(self, name).
__dir__()Default dir() implementation.
__eq__(value, /)Return self==value.
__format__(format_spec, /)Default object formatter.
__ge__(value, /)Return self>=value.
__getattribute__(name, /)Return getattr(self, name).
__getstate__()Helper for pickle.
__gt__(value, /)Return self>value.
__hash__()Return hash(self).
__init__([fig, builder])Initiate the instance.
__init_subclass__()This method is called when a class is subclassed.
__le__(value, /)Return self<=value.
__lt__(value, /)Return self<value.
__ne__(value, /)Return self!=value.
__new__(*args, **kwargs)__reduce__()Helper for pickle.
__reduce_ex__(protocol, /)Helper for pickle.
__repr__()Return repr(self).
__setattr__(name, value, /)Implement setattr(self, name, value).
__sizeof__()Size of object in memory, in bytes.
__str__()Return str(self).
__subclasshook__(object, /)Abstract classes can override this to customize issubclass().
_animate(i)Update the data of the plot.
Check if a subplot name is not used in two different subfigures.
_gather_figure_legend_items([fig_name, ...])Gather the legend items from all axes of the figure or of one subfigure.
_get_axis_legend_items(ax_name)Get the given axis legend handles and labels.
_get_bbox_extra_artists([kwargs])Only required for blitting to give a clean slate.
_iterate_subfig_grouped_axes(subfig_name)_remove_dulicated_legend_items(handles, labels)Remove the duplicated legend handles and labels.
add_axis_legend(ax_name[, is_reverse_items])Add a legend to the graphic.
add_axis_legend_outside_frame(ax_name[, ...])Add a legend to the ax outside the ax frame.
add_extra_legend_item(ax_name, handle, label)Add an extra legend item to the given axis.
add_fig_legend([name, bbox_x_shift, ...])Add a legend to the plot.
Add a grid to all the axes of the figure.
animate(nb_frames[, blit])Animate the plot.
animated_multi_imshow(ax_names, data[, fig, ...])Plot an animated 2D field with imshow.
animated_multi_plot(ax_name, data[, ...])Plot a 1D animated curves.
Clear all the axes from their data and layouts.
Remove all added figure legends
close()Close the current figure.
get_axes(ax_names)Get a sequence of axes from the plotter.
get_axis(ax_name)Get an axis from the plotter.
get_subfigure(subfig_name)Get an axis from the plotter.
get_subfigure_ax_dict(subfig_name)identify_axes([fontsize])Draw the label in a large font in the center of the Axes.
plot_animated_text(ax, x, y, s, **kwargs)Add a text animation to the given axis.
save_animation(filename[, writer, fps, dpi, ...])Save the animation as a movie file by drawing every frame.
savefig(*args, **kwargs)Save the current figure.
Methods definition
- static _remove_dulicated_legend_items(handles: Sequence[Artist], labels: Sequence[str]) Tuple[List[Artist], List[str]]#
Remove the duplicated legend handles and labels.
- _check_if_subplot_names_are_unique() None#
Check if a subplot name is not used in two different subfigures.
This is necessary otherwise, one or more subplots would be missing from the ax_dict.
- Raises:
Exception – Indicate which axis names are duplicated and on which subfigures .
- Return type:
None
- _gather_figure_legend_items(fig_name: str | None = None, remove_duplicates: bool = True) Tuple[List[Artist], List[str]]#
Gather the legend items from all axes of the figure or of one subfigure.
- Parameters:
- Returns:
Handles and labels lists.
- Return type:
Tuple[List[Artist], List[str]]
- _get_axis_legend_items(ax_name: str) Tuple[List[Artist], List[str]]#
Get the given axis legend handles and labels.
- add_axis_legend(ax_name: str, is_reverse_items: bool = False, **kwargs: Any) Tuple[List[Any], List[str]]#
Add a legend to the graphic.
- Parameters:
- Returns:
Tuple of list of handles and list of associated labels.
- Return type:
(Tuple[List[Any], List[str]])
- add_axis_legend_outside_frame(ax_name: str, bbox_x_shift: float | None = None, bbox_y_shift: float | None = None, loc: Literal['left', 'right', 'top', 'bottom'] = 'bottom', borderaxespad: float = 1.0, is_reverse_items: bool = False, **kwargs: Any) Legend | None#
Add a legend to the ax outside the ax frame.
- Parameters:
ax_name (str) – The name of the ax for which to add a legend outside the frame.
bbox_x_shift (float, optional) – Legend vertical shift (up oriented). The default is 0.0.
bbox_y_shift (float, optional) – Legend horizontal shift (right oriented). The default is 0.0.
loc (Literal["left", "right", "top", "bottom"], optional) – Side on which to place the legend box. The default is “bottom”.
is_reverse_items (bool) – Whether to reverse the order of items in the legend. The default is False. .. versionadded:: 2.0
**kwargs (Any) – Additional arguments for plt.legend.
- Returns:
The created legend instance. None if no handles nor labels have been found.
- Return type:
Optional[Legend]
- add_extra_legend_item(ax_name: str, handle: Any, label: str) None#
Add an extra legend item to the given axis.
- add_fig_legend(name: str | None = None, bbox_x_shift: float = 0.0, bbox_y_shift: float = 0.0, loc: Literal['left', 'right', 'top', 'bottom'] = 'bottom', is_reverse_items: bool = False, **kwargs: Any) Legend | None#
Add a legend to the plot.
To the main figure or to one subfigure.
- Parameters:
name (Optional[str], optional) – The subfigure to which add the legend. If no name is given, it applies to the all figure. Otherwise to a specific subfigure. The default is None.
bbox_x_shift (float, optional) – Legend vertical shift (up oriented). The default is 0.0.
bbox_y_shift (float, optional) – Legend horizontal shift (right oriented). The default is 0.0.
loc (Literal["left", "right", "top", "bottom"], optional) – Side on which to place the legend box. The default is “bottom”.
is_reverse_items (bool) – Whether to reverse the order of items in the legend. The default is False. .. versionadded:: 2.0
**kwargs (Any) – Additional arguments for plt.legend.
- Returns:
The created legend instance. None if no handles nor labels have been found.
- Return type:
Optional[Legend]
- add_grid_and_tick_prams_to_all_axes(subfigure_name: str | None = None, **kwargs: Any) None#
Add a grid to all the axes of the figure.
- Parameters:
subfigure_name (Optional[str], optional) – Name of the target subfigure. If None, apply to the all figure. The default is None.
**kwargs (Any) – Keywords for add_grid_and_thick_prams_to_axis.
- Return type:
None
- animate(nb_frames: int, blit: bool = True) FuncAnimation[source]#
Animate the plot.
- Parameters:
nb_frames (int) – The number of frames to consider for the animation.
blit (bool, optional) – Whether blitting is used to optimize drawing. Note: when using blitting, any animated artists will be drawn according to their zorder; however, they will be drawn on top of any previous artists, regardless of their zorder. The default is True.
- Returns:
The animation.
- Return type:
animation.FuncAnimation
- animated_multi_imshow(ax_names: Sequence[str], data: Dict[str, ndarray[tuple[Any, ...], dtype[float64]]], fig: Figure | SubFigure | None = None, nb_frames: int | None = None, xlabel: str | None = None, ylabel: str | None = None, imshow_kwargs: Dict[str, Any] | None = None, cbar_kwargs: Dict[str, Any] | None = None, is_symmetric_cbar: bool = False, cbar_title: str | None = None) Colorbar[source]#
Plot an animated 2D field with imshow.
The number of frames can be determined automatically from the data.
- Parameters:
ax_names (str) – List of axis names in which to plot the data. The order of axes must be the same as that of the data.
data (Dict[str, Union[np.ndarray, Dict[str, Any]]]) – Data to be plotted.
fig (Optional[Figure, SubFigure]) – Which figure to consider for the color bar. By default, use self.fig.
nb_frames (Optional[int]) – Number of frame to use. By default, it is the number of provided steps, that is to say the last dimension of the arrays. If the number of frames exceeds the number of steps available, some steps will be repeated once or more and a warning is raised.
xlabel (Optional[str], optional) – Label to apply to all xaxes. The default is None.
ylabel (Optional[str], optional) – Label to apply to all yaxes. The default is None.
imshow_kwargs (Optional[Dict[str, Any]] optional) – Optional arguments for plt.imshow. The default is None.
Examples
Examples can be given using either the
ExampleorExamplessections. Sections support any reStructuredText formatting, including literal blocks:$ python example_numpy.py
- Raises:
ValueError – If the provided data dictionary contains inconsistent arrays.
- Return type:
None
- animated_multi_plot(ax_name: str, data: Dict[str, Dict[str, Any]], nb_frames: int | None = None, title: str | None = None, xlabel: str | None = None, ylabel: str | None = None) None[source]#
Plot a 1D animated curves.
The number of frames can be determined automatically from the data.
- Parameters:
ax_name (str) – Name of the axis on which to plot the animation.
nb_frames (int) – Number of frames to use in the animation. If None, the second dimension of the provided data arrays is used.
title (Optional[str], optional) – Title to give to the plot. The default is None.
xlabel (Optional[str], optional) – Label for the xaxis. The default is None.
ylabel (Optional[str], optional) – Label for the yaxis. The default is None.
- Raises:
ValueError – If the provided data dictionary contains inconsistent arrays.
- Return type:
None
- clear_all_axes() None#
Clear all the axes from their data and layouts.
It also resets the additional handles and labels for the legend.
- get_axes(ax_names: Sequence[str]) List[Axes]#
Get a sequence of axes from the plotter.
- Parameters:
ax_names (Sequence[str]) – Name of the axes to get. Must be iterable.
- Returns:
The desired axes.
- Return type:
Axes
- get_axis(ax_name: str) Axes#
Get an axis from the plotter.
- Parameters:
ax_name (str) – Name of the axis to get.
- Returns:
The desired axis.
- Return type:
Axes
- get_subfigure(subfig_name: str) SubFigure#
Get an axis from the plotter.
- Parameters:
subfig_name (str) – Name of the subfigure to get.
- Returns:
The desired subfigure.
- Return type:
SubFigure
- plot_animated_text(ax: Axes, x: float, y: float, s: Sequence[str], **kwargs: Any) None[source]#
Add a text animation to the given axis.
- save_animation(filename: str | Path, writer: MovieWriter | None = None, fps: int | None = None, dpi: float | None = None, codec: str | None = None, bitrate: int | None = None, extra_args: List[str] | None = None, metadata: Dict[str, str] | None = None, extra_anim: List[Animation] | None = None, savefig_kwargs: Dict[str, Any] | None = None, *, progress_callback: Callable | None = None) None[source]#
Save the animation as a movie file by drawing every frame.
- Parameters:
filename (str) – The output filename, e.g.,
mymovie.mp4.writer (MovieWriter or str, default: :rc:`animation.writer`) – A MovieWriter instance to use or a key that identifies a class to use, such as ‘ffmpeg’.
fps (int, optional) – Movie frame rate (per second). If not set, the frame rate from the animation’s frame interval.
dpi (float, default: :rc:`savefig.dpi`) – Controls the dots per inch for the movie frames. Together with the figure’s size in inches, this controls the size of the movie.
codec (str, default: :rc:`animation.codec`.) – The video codec to use. Not all codecs are supported by a given MovieWriter.
bitrate (int, default: :rc:`animation.bitrate`) – The bitrate of the movie, in kilobits per second. Higher values means higher quality movies, but increase the file size. A value of -1 lets the underlying movie encoder select the bitrate.
extra_args (list of str or None, optional) – Extra command-line arguments passed to the underlying movie encoder. These arguments are passed last to the encoder, just before the output filename. The default, None, means to use :rc:`animation.[name-of-encoder]_args` for the builtin writers.
metadata (dict[str, str], default: {}) – Dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment.
extra_anim (list, default: []) – Additional Animation objects that should be included in the saved movie file. These need to be from the same .Figure instance. Also, animation frames will just be simply combined, so there should be a 1:1 correspondence between the frames from the different animations.
savefig_kwargs (dict, default: {}) – Keyword arguments passed to each ~.Figure.savefig call used to save the individual frames.
progress_callback (function, optional) –
A callback function that will be called for every frame to notify the saving progress. It must have the signature
def func(current_frame: int, total_frames: int) -> Any
where current_frame is the current frame number and total_frames is the total number of frames to be saved. total_frames is set to None, if the total number of frames cannot be determined. Return values may exist but are ignored.
Example code to write the progress to stdout:
progress_callback = lambda i, n: print(f'Saving frame {i}/{n}')
Notes
fps, codec, bitrate, extra_args and metadata are used to construct a .MovieWriter instance and can only be passed if writer is a string. If they are passed as non-None and writer is a .MovieWriter, a RuntimeError will be raised.
- savefig(*args: Any, **kwargs: Any) None#
Save the current figure.
- Parameters:
*args (Any) – Positional arguments for
matplotlib.figure.Figure.savefig().**kwargs (Any) – Keywords arguments for
matplotlib.figure.Figure.savefig().
- Return type:
None
- property animation: FuncAnimation#
Get the animation or raise an attribute error if not defined.