yt.visualization.plot_window module¶
- class yt.visualization.plot_window.AxisAlignedProjectionPlot(ds, normal, fields, *args, **kwargs)[source]¶
Bases:
ProjectionPlot
,PWViewerMPL
Creates a projection plot from a dataset
Given a ds object, an axis to project along, and a field name string, this will return a PWViewerMPL object containing the plot.
The plot can be updated using one of the many helper functions defined in PlotWindow.
- Parameters:
ds (Dataset) – This is the dataset object corresponding to the simulation output to be plotted.
normal (int or one of 'x', 'y', 'z') – An int corresponding to the axis to slice along (0=x, 1=y, 2=z) or the axis name itself
fields (string) – The name of the field(s) to be plotted.
center ('center', 'c', 'left', 'l', 'right', 'r', id of a global extremum, or array-like) –
The coordinate of the selection’s center. Defaults to the ‘center’, i.e. center of the domain.
Centering on the min or max of a field is supported by passing a tuple such as (‘min’, (‘gas’, ‘density’)) or (‘max’, (‘gas’, ‘temperature’). A single string may also be used (e.g. “min_density” or “max_temperature”), though it’s not as flexible and does not allow to select an exact field/particle type. With this syntax, the first field matching the provided name is selected. ‘max’ or ‘m’ can be used as a shortcut for (‘max’, (‘gas’, ‘density’)) ‘min’ can be used as a shortcut for (‘min’, (‘gas’, ‘density’))
One can also select an exact point as a 3 element coordinate sequence, e.g. [0.5, 0.5, 0] Units can be specified by passing in center as a tuple containing a 3-element coordinate sequence and string unit name, e.g. ([0, 0.5, 0.5], “cm”), or by passing in a YTArray. Code units are assumed if unspecified.
The domain edges along the selected axis can be selected with ‘left’/’l’ and ‘right’/’r’ respectively.
width (tuple or a float.) –
Width can have four different formats to support windows with variable x and y widths. They are:
format
example
(float, string)
(10,’kpc’)
((float, string), (float, string))
((10,’kpc’),(15,’kpc’))
float
0.2
(float, float)
(0.2, 0.3)
For example, (10, ‘kpc’) requests a plot window that is 10 kiloparsecs wide in the x and y directions, ((10,’kpc’),(15,’kpc’)) requests a window that is 10 kiloparsecs wide along the x axis and 15 kiloparsecs wide along the y axis. In the other two examples, code units are assumed, for example (0.2, 0.3) requests a plot that has an x width of 0.2 and a y width of 0.3 in code units. If units are provided the resulting plot axis labels will use the supplied units.
axes_unit (string) – The name of the unit for the tick labels on the x and y axes. Defaults to None, which automatically picks an appropriate unit. If axes_unit is ‘1’, ‘u’, or ‘unitary’, it will not display the units, and only show the axes name.
origin (string or length 1, 2, or 3 sequence.) –
The location of the origin of the plot coordinate system. This is typically represented by a ‘-’ separated string or a tuple of strings. In the first index the y-location is given by ‘lower’, ‘upper’, or ‘center’. The second index is the x-location, given as ‘left’, ‘right’, or ‘center’. Finally, whether the origin is applied in ‘domain’ space, plot ‘window’ space or ‘native’ simulation coordinate system is given. For example, both ‘upper-right-domain’ and [‘upper’, ‘right’, ‘domain’] place the origin in the upper right hand corner of domain space. If x or y are not given, a value is inferred. For instance, ‘left-domain’ corresponds to the lower-left hand corner of the simulation domain, ‘center-domain’ corresponds to the center of the simulation domain, or ‘center-window’ for the center of the plot window. In the event that none of these options place the origin in a desired location, a sequence of tuples and a string specifying the coordinate space can be given. If plain numeric types are input, units of code_length are assumed. Further examples:
format
example
’{space}’
’domain’
’{xloc}-{space}’
’left-window’
’{yloc}-{space}’
’upper-domain’
’{yloc}-{xloc}-{space}’
’lower-right-window’
(‘{space}’,)
(‘window’,)
(‘{xloc}’, ‘{space}’)
(‘right’, ‘domain’)
(‘{yloc}’, ‘{space}’)
(‘lower’, ‘window’)
(‘{yloc}’, ‘{xloc}’, ‘{space}’)
(‘lower’, ‘right’, ‘window’)
((yloc, ‘{unit}’), (xloc, ‘{unit}’), ‘{space}’)
((0, ‘m’), (.4, ‘m’), ‘window’)
(xloc, yloc, ‘{space}’)
(0.23, 0.5, ‘domain’)
data_source (YTSelectionContainer object) – Object to be used for data selection. Defaults to a region covering the entire simulation.
weight_field (string) – The name of the weighting field. Set to None for no weight.
max_level (int) – The maximum level to project to.
fontsize (integer) – The size of the fonts for the axis, colorbar, and tick labels.
method (string) –
The method of projection. Valid methods are:
”integrate” with no weight_field specified : integrate the requested field along the line of sight.
”integrate” with a weight_field specified : weight the requested field by the weighting field and integrate along the line of sight.
”max” : pick out the maximum value of the field in the line of sight. “min” : pick out the minimum value of the field in the line of sight.
”sum” : This method is the same as integrate, except that it does not multiply by a path length when performing the integration, and is just a straight summation of the field along the given axis. WARNING: This should only be used for uniform resolution grid datasets, as other datasets may result in unphysical images.
window_size (float) – The size of the window in inches. Set to 8 by default.
aspect (float) – The aspect ratio of the plot. Set to None for 1.
field_parameters (dictionary) – A dictionary of field parameters than can be accessed by derived fields.
data_source – Object to be used for data selection. Defaults to ds.all_data(), a region covering the full domain
buff_size (length 2 sequence) – Size of the buffer to use for the image, i.e. the number of resolution elements used. Effectively sets a resolution limit to the image if buff_size is smaller than the finest gridding.
moment (integer, optional) – for a weighted projection, moment = 1 (the default) corresponds to a weighted average. moment = 2 corresponds to a weighted standard deviation.
Examples
Create a projection plot with a width of 20 kiloparsecs centered on the center of the simulation box:
>>> from yt import load >>> ds = load("IsolateGalaxygalaxy0030/galaxy0030") >>> p = AxisAlignedProjectionPlot(ds, "z", ("gas", "density"), width=(20, "kpc"))
- annotate_arrow(pos, *, length=0.03, width=0.0001, head_width=0.01, head_length=0.01, starting_pos=None, coord_system='data', plot_args: dict[str, Any] | None = None, **kwargs)¶
Overplot arrow(s) pointing at position(s) for highlighting specific features. By default, arrow points from lower left to the designated position “pos” with arrow length “length”. Alternatively, if “starting_pos” is set, arrow will stretch from “starting_pos” to “pos” and “length” will be disregarded.
“coord_system” keyword refers to positions set in “pos” arg and “starting_pos” keyword, which by default are in data coordinates.
“length”, “width”, “head_length”, and “head_width” keywords for the arrow are all in axis units, ie relative to the size of the plot axes as 1, even if the position of the arrow is set relative to another coordinate system.
- Parameters:
pos (array-like) – These are the coordinates where the marker(s) will be overplotted Either as [x,y,z] or as [[x1,x2,…],[y1,y2,…],[z1,z2,…]]
length (float, optional) – The length, in axis units, of the arrow. Default: 0.03
width (float, optional) – The width, in axis units, of the tail line of the arrow. Default: 0.003
head_length (float, optional) – The length, in axis units, of the head of the arrow. If set to None, use 1.5*head_width Default: None
head_width (float, optional) – The width, in axis units, of the head of the arrow. Default: 0.02
starting_pos (2- or 3-element tuple, list, or array, optional) – These are the coordinates from which the arrow starts towards its point. Not compatible with ‘length’ kwarg.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
plot_args (dictionary, optional) – This dictionary is passed to the MPL arrow function for generating the arrow. By default, it is: {‘color’:’white’}
Examples
>>> # Overplot an arrow pointing to feature at data coord: (0.2, 0.3, 0.4) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_arrow([0.2, 0.3, 0.4]) >>> s.save()
>>> # Overplot a red arrow with longer length pointing to plot coordinate >>> # (0.1, -0.1) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_arrow( ... [0.1, -0.1], length=0.06, coord_system="plot", color="red" ... ) >>> s.save()
- annotate_cell_edges(line_width=0.002, alpha=1.0, color='black')¶
Annotate cell edges. This is done through a second call to pixelize, where the distance from a pixel to a cell boundary in pixels is compared against the line_width argument. The secondary image is colored as color and overlaid with the alpha value.
- Parameters:
line_width (float) – The width of the cell edge lines in normalized units relative to the size of the longest axis. Default is 1% of the size of the smallest axis.
alpha (float) – When the second image is overlaid, it will have this level of alpha transparency. Default is 1.0 (fully-opaque).
color (tuple of three floats or matplotlib color name) – This is the color of the cell edge values. It defaults to black.
Examples
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_cell_edges() >>> s.save()
- annotate_clumps(clumps, *, plot_args=None, **kwargs)¶
Take a list of clumps and plot them as a set of contours.
- annotate_contour(field: tuple[str, str] | str, levels: int = 5, *, factor: tuple[int, int] | int = 4, clim: tuple[float, float] | None = None, label: bool = False, take_log: bool | None = None, data_source: YTDataContainer | None = None, plot_args: dict[str, Any] | None = None, text_args: dict[str, Any] | None = None, ncont: int | None = None) None ¶
Add contours in field to the plot. levels governs the number of contours generated, factor governs the number of points used in the interpolation, take_log governs how it is contoured and clim gives the (lower, upper) limits for contouring. An alternate data source can be specified with data_source, but by default the plot’s data source will be queried.
- annotate_cquiver(field_x, field_y, field_c=None, *, factor: tuple[int, int] | int = 16, scale=None, scale_units=None, normalize=False, plot_args=None, **kwargs)¶
Get a quiver plot on top of a cutting plane, using field_x and field_y, skipping every factor datapoint in the discretization. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- annotate_grids(alpha=0.7, min_pix=1, min_pix_ids=20, draw_ids=False, id_loc=None, periodic=True, min_level=None, max_level=None, cmap='B-W LINEAR_r', edgecolors=None, linewidth=1.0)¶
Draws grids on an existing PlotWindow object. Adds grid boundaries to a plot, optionally with alpha-blending. By default, colors different levels of grids with different colors going from white to black, but you can change to any arbitrary colormap with cmap keyword, to all black grid edges for all levels with cmap=None and edgecolors=None, or to an arbitrary single color for grid edges with edgecolors=’YourChosenColor’ defined in any of the standard ways (e.g., edgecolors=’white’, edgecolors=’r’, edgecolors=’#00FFFF’, or edgecolor=’0.3’, where the last is a float in 0-1 scale indicating gray). Note that setting edgecolors overrides cmap if you have both set to non-None values. Cutoff for display is at min_pix wide. draw_ids puts the grid id a the corner of the grid (but its not so great in projections…). id_loc determines which corner holds the grid id. One can set min and maximum level of grids to display, and can change the linewidth of the displayed grids.
- annotate_line(p1, p2, *, coord_system='data', plot_args: dict[str, Any] | None = None, **kwargs)¶
Overplot a line with endpoints at p1 and p2. p1 and p2 should be 2D or 3D coordinates consistent with the coordinate system denoted in the “coord_system” keyword.
- Parameters:
p1 (2- or 3-element tuples, lists, or arrays) – These are the coordinates of the endpoints of the line.
p2 (2- or 3-element tuples, lists, or arrays) – These are the coordinates of the endpoints of the line.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates p1 and p2. Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
plot_args (dictionary, optional) – This dictionary is passed to the MPL plot function for generating the line. By default, it is: {‘color’:’white’, ‘linewidth’:2}
Examples
>>> # Overplot a diagonal white line from the lower left corner to upper >>> # right corner >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_line([0, 0], [1, 1], coord_system="axis") >>> s.save()
>>> # Overplot a red dashed line from data coordinate (0.1, 0.2, 0.3) to >>> # (0.5, 0.6, 0.7) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_line( ... [0.1, 0.2, 0.3], ... [0.5, 0.6, 0.7], ... coord_system="data", ... color="red", ... linestyles="--", ... ) >>> s.save()
- annotate_line_integral_convolution(field_x, field_y, texture=None, kernellen=50.0, lim=(0.5, 0.6), cmap='binary', alpha=0.8, const_alpha=False)¶
Add the line integral convolution to the plot for vector fields visualization. Two component of vector fields needed to be provided (i.e., velocity_x and velocity_y, magnetic_field_x and magnetic_field_y).
- Parameters:
field_x (string) – The names of two components of vector field which will be visualized
field_y (string) – The names of two components of vector field which will be visualized
texture (2-d array with the same shape of image, optional) – Texture will be convolved when computing line integral convolution. A white noise background will be used as default.
kernellen (float, optional) – The lens of kernel for convolution, which is the length over which the convolution will be performed. For longer kernellen, longer streamline structure will appear.
lim (2-element tuple, list, or array, optional) – The value of line integral convolution will be clipped to the range of lim, which applies upper and lower bounds to the values of line integral convolution and enhance the visibility of plots. Each element should be in the range of [0,1].
cmap (string, optional) – The name of colormap for line integral convolution plot.
alpha (float, optional) – The alpha value for line integral convolution plot.
const_alpha (boolean, optional) – If set to False (by default), alpha will be weighted spatially by the values of line integral convolution; otherwise a constant value of the given alpha is used.
Example
>>> import yt >>> ds = yt.load("Enzo_64/DD0020/data0020") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_line_integral_convolution( ... "velocity_x", "velocity_y", lim=(0.5, 0.65) ... )
- annotate_magnetic_field(factor: tuple[int, int] | int = 16, *, scale=None, scale_units=None, normalize=False, plot_args=None, **kwargs)¶
Adds a ‘quiver’ plot of magnetic field to the plot, skipping all but every factor datapoint. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the magnetic fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- annotate_marker(pos, marker='x', *, coord_system='data', plot_args=None, **kwargs)¶
Overplot marker(s) at a position(s) for highlighting specific features.
- Parameters:
pos (array-like) – These are the coordinates where the marker(s) will be overplotted Either as [x,y,z] or as [[x1,x2,…],[y1,y2,…],[z1,z2,…]]
marker (string, optional) – The shape of the marker to be passed to the MPL scatter function. By default, it is ‘x’, but other acceptable values are: ‘.’, ‘o’, ‘v’, ‘^’, ‘s’, ‘p’ ‘*’, etc. See matplotlib.markers for more information.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
plot_args (dictionary, optional) – This dictionary is passed to the MPL scatter function for generating the marker. By default, it is: {‘color’:’white’, ‘s’:50}
Examples
>>> # Overplot a white X on a feature at data location (0.5, 0.5, 0.5) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_marker([0.4, 0.5, 0.6]) >>> s.save()
>>> # Overplot a big yellow circle at axis location (0.1, 0.2) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_marker( ... [0.1, 0.2], ... marker="o", ... coord_system="axis", ... color="yellow", ... s=200, ... ) >>> s.save()
- annotate_mesh_lines(*, plot_args=None, **kwargs)¶
Adds mesh lines to the plot. Only works for unstructured or semi-structured mesh data. For structured grid data, see GridBoundaryCallback or CellEdgesCallback.
- Parameters:
plot_args (dict, optional) – A dictionary of arguments that will be passed to matplotlib.
Example
>>> import yt >>> ds = yt.load("MOOSE_sample_data/out.e-s010") >>> sl = yt.SlicePlot(ds, "z", ("connect2", "convected")) >>> sl.annotate_mesh_lines(color="black")
- annotate_particles(width, p_size=1.0, col='k', marker='o', stride=1, ptype='all', alpha=1.0, data_source=None)¶
Adds particle positions, based on a thick slab along axis with a width along the line of sight. p_size controls the number of pixels per particle, and col governs the color. ptype will restrict plotted particles to only those that are of a given type. alpha determines the opacity of the marker symbol used in the scatter. An alternate data source can be specified with data_source, but by default the plot’s data source will be queried.
- annotate_quiver(field_x, field_y, field_c=None, *, factor: tuple[int, int] | int = 16, scale=None, scale_units=None, normalize=False, bv_x=0, bv_y=0, plot_args=None, **kwargs)¶
Adds a ‘quiver’ plot to any plot, using the field_x and field_y from the associated data, skipping every factor pixels. field_c is an optional field name used for color. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- annotate_ray(ray, *, arrow=False, plot_args=None, **kwargs)¶
Adds a line representing the projected path of a ray across the plot. The ray can be either a YTOrthoRay, YTRay, or a LightRay object. annotate_ray() will properly account for periodic rays across the volume. If arrow is set to True, uses the MPL.pyplot.arrow function, otherwise uses the MPL.pyplot.plot function to plot a normal line. Adjust plot_args accordingly.
- Parameters:
ray (YTOrthoRay, YTRay, or LightRay) – Ray is the object that we want to include. We overplot the projected trajectory of the ray. If the object is a trident.LightRay object, it will only plot the segment of the LightRay that intersects the dataset currently displayed.
arrow (boolean, optional) – Whether or not to place an arrowhead on the front of the ray to denote direction Default: False
plot_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib line object. Defaults: {‘color’:’white’, ‘linewidth’:2}.
Examples
>>> # Overplot a ray and an ortho_ray object on a projection >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> oray = ds.ortho_ray(1, (0.3, 0.4)) # orthoray down the y axis >>> ray = ds.ray((0.1, 0.2, 0.3), (0.6, 0.7, 0.8)) # arbitrary ray >>> p = yt.ProjectionPlot(ds, "z", "density") >>> p.annotate_ray(oray) >>> p.annotate_ray(ray) >>> p.save()
>>> # Overplot a LightRay object on a projection >>> import yt >>> from trident import LightRay >>> ds = yt.load("enzo_cosmology_plus/RD0004/RD0004") >>> lr = LightRay( ... "enzo_cosmology_plus/AMRCosmology.enzo", "Enzo", 0.0, 0.1, time_data=False ... ) >>> lray = lr.make_light_ray(seed=1) >>> p = yt.ProjectionPlot(ds, "z", "density") >>> p.annotate_ray(lr) >>> p.save()
- annotate_scale(*, corner='lower_right', coeff=None, unit=None, pos=None, max_frac=0.16, min_frac=0.015, coord_system='axis', text_args=None, size_bar_args=None, draw_inset_box=False, inset_box_args=None, scale_text_format='{scale} {units}')¶
Annotates the scale of the plot at a specified location in the image (either in a preset corner, or by specifying (x,y) image coordinates with the pos argument. Coeff and units (e.g. 1 Mpc or 100 kpc) refer to the distance scale you desire to show on the plot. If no coeff and units are specified, an appropriate pair will be determined such that your scale bar is never smaller than min_frac or greater than max_frac of your plottable axis length. Additional customization of the scale bar is possible by adjusting the text_args and size_bar_args dictionaries. The text_args dictionary accepts matplotlib’s font_properties arguments to override the default font_properties for the current plot. The size_bar_args dictionary accepts keyword arguments for the AnchoredSizeBar class in matplotlib’s axes_grid toolkit.
- Parameters:
corner (string, optional) – Corner sets up one of 4 predeterimined locations for the scale bar to be displayed in the image: ‘upper_left’, ‘upper_right’, ‘lower_left’, ‘lower_right’ (also allows None). This value will be overridden by the optional ‘pos’ keyword.
coeff (float, optional) – The coefficient of the unit defining the distance scale (e.g. 10 kpc or 100 Mpc) for overplotting. If set to None along with unit keyword, coeff will be automatically determined to be a power of 10 relative to the best-fit unit.
unit (string, optional) – unit must be a valid yt distance unit (e.g. ‘m’, ‘km’, ‘AU’, ‘pc’, ‘kpc’, etc.) or set to None. If set to None, will be automatically determined to be the best-fit to the data.
pos (2- or 3-element tuples, lists, or arrays, optional) – The image location of the scale bar in the plot coordinate system. Setting pos overrides the corner parameter.
min_frac (float, optional) – The minimum/maximum fraction of the axis width for the scale bar to extend. A value of 1 would allow the scale bar to extend across the entire axis width. Only used for automatically calculating best-fit coeff and unit when neither is specified, otherwise disregarded.
max_frac (float, optional) – The minimum/maximum fraction of the axis width for the scale bar to extend. A value of 1 would allow the scale bar to extend across the entire axis width. Only used for automatically calculating best-fit coeff and unit when neither is specified, otherwise disregarded.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data”: 3D dataset coordinates
”plot”: 2D coordinates defined by the actual plot limits
”axis”: MPL axis coordinates: (0,0) is lower left; (1,1) is upper right
”figure”: MPL figure coordinates: (0,0) is lower left, (1,1) is upper right
text_args (dictionary, optional) – A dictionary of parameters to used to update the font_properties for the text in this callback. For any property not set, it will use the defaults of the plot. Thus one can modify the text size with
text_args={'size':24}
size_bar_args (dictionary, optional) – A dictionary of parameters to be passed to the Matplotlib AnchoredSizeBar initializer. Defaults:
{'pad': 0.25, 'sep': 5, 'borderpad': 1, 'color': 'w'}
draw_inset_box (boolean, optional) – Whether or not an inset box should be included around the scale bar.
inset_box_args (dictionary, optional) – A dictionary of keyword arguments to be passed to the matplotlib Patch object that represents the inset box. Defaults:
{'facecolor': 'black', 'linewidth': 3, 'edgecolor': 'white', 'alpha': 0.5, 'boxstyle': 'square'}
scale_text_format (string, optional) – This specifies the format of the scalebar value assuming “scale” is the numerical value and “unit” is units of the scale (e.g. ‘cm’, ‘kpc’, etc.) The scale can be specified to arbitrary precision according to printf formatting codes. The format string must only specify “scale” and “units”. Example: “Length = {scale:.2f} {units}”. Default: “{scale} {units}”
Example
>>> import yt >>> ds = yt.load("Enzo_64/DD0020/data0020") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_scale()
- annotate_sphere(center, radius, *, coord_system='data', text=None, circle_args=None, text_args=None)¶
Overplot a circle with designated center and radius with optional text.
- Parameters:
center (2- or 3-element tuple, list, or array) – These are the coordinates where the circle will be overplotted
radius (YTArray, float, or (1, ('kpc')) style tuple) – The radius of the circle in code coordinates
circle_args (dict, optional) – This dictionary is passed to the MPL circle object. By default, {‘color’:’white’}
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
text (string, optional) – Optional text to include next to the circle.
text_args (dictionary, optional) – This dictionary is passed to the MPL text function. By default, it is: {‘color’:’white’}
Examples
>>> # Overplot a white circle of radius 100 kpc over the central galaxy >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_sphere([0.5, 0.5, 0.5], radius=(100, "kpc")) >>> s.save()
- annotate_streamlines(field_x: tuple[str, str] | str, field_y: tuple[str, str] | str, *, linewidth: float | tuple[str, str] | str = 1.0, linewidth_upscaling: float = 1.0, color: Any | tuple[str, str] | None = None, color_threshold: float | unyt_quantity = -inf, factor: tuple[int, int] | int = 16, field_color=None, display_threshold=None, plot_args=None, **kwargs)¶
Plot streamlines using matplotlib.axes.Axes.streamplot
- Parameters:
field_x (field key) – The “velocity” analoguous field along the horizontal direction.
field_y (field key) – The “velocity” analoguous field along the vertical direction.
linewidth (float, or field key (default: 1.0)) – A constant scalar will be passed directly to matplotlib.axes.Axes.streamplot A field key will be first interpreted by yt and produce the adequate 2D array. Data fields are normalized by their maximum value, so the maximal linewidth is 1 by default. See linewidth_upscaling for fine tuning. Note that the absolute value is taken in all cases.
linewidth_upscaling (float (default: 1.0)) – A constant multiplicative factor applied to linewidth. Final linewidth is obtained as: linewidth_upscaling * abs(linewidth) / max(abs(linewidth))
color (a color identifier, or a field key (default: matplotlib.rcParams['line.color'])) – A constant color identifier will be passed directly to matplotlib.axes.Axes.streamplot A field key will be first interpreted by yt and produce the adequate 2D array. See https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.streamplot.html for how to customize color mapping using cmap and norm arguments.
color_threshold (float or unyt_quantity (default: -inf)) – Regions where the field used for color is lower than this threshold will be masked. Only used if color is a field key.
factor (int, or tuple[int, int] (default: 16)) – Fields are downed-sampled by this factor with respect to the background image buffer size. A single integer factor will be used for both direction, but a tuple of 2 integers can be passed to set x and y downsampling independently.
**kwargs (any additional keyword arguments will be passed) – directly to matplotlib.axes.Axes.streamplot
- annotate_text(pos, text, *, coord_system='data', text_args=None, inset_box_args=None)¶
Overplot text on the plot at a specified position. If you desire an inset box around your text, set one with the inset_box_args dictionary keyword.
- Parameters:
pos (2- or 3-element tuple, list, or array) – These are the coordinates where the text will be overplotted
text (string) – The text you wish to include
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
text_args (dictionary, optional) – This dictionary is passed to the MPL text function for generating the text. By default, it is: {‘color’:’white’} and uses the defaults for the other fonts in the image.
inset_box_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib FancyBboxPatch object as the inset box around the text. Default: {}
Examples
>>> # Overplot white text at data location [0.55, 0.7, 0.4] >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_text([0.55, 0.7, 0.4], "Here is a galaxy") >>> s.save()
>>> # Overplot yellow text at axis location [0.2, 0.8] with >>> # a shaded inset box >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_text( ... [0.2, 0.8], ... "Here is a galaxy", ... coord_system="axis", ... text_args={"color": "yellow"}, ... inset_box_args={ ... "boxstyle": "square,pad=0.3", ... "facecolor": "black", ... "linewidth": 3, ... "edgecolor": "white", ... "alpha": 0.5, ... }, ... ) >>> s.save()
- annotate_timestamp(x_pos=None, y_pos=None, corner='lower_left', *, time=True, redshift=False, time_format='t = {time:.1f} {units}', time_unit=None, redshift_format='z = {redshift:.2f}', draw_inset_box=False, coord_system='axis', time_offset=None, text_args=None, inset_box_args=None)¶
Annotates the timestamp and/or redshift of the data output at a specified location in the image (either in a present corner, or by specifying (x,y) image coordinates with the x_pos, y_pos arguments. If no time_units are specified, it will automatically choose appropriate units. It allows for custom formatting of the time and redshift information, as well as the specification of an inset box around the text.
- Parameters:
x_pos (floats, optional) – The image location of the timestamp in the coord system defined by the coord_system kwarg. Setting x_pos and y_pos overrides the corner parameter.
y_pos (floats, optional) – The image location of the timestamp in the coord system defined by the coord_system kwarg. Setting x_pos and y_pos overrides the corner parameter.
corner (string, optional) – Corner sets up one of 4 predeterimined locations for the timestamp to be displayed in the image: ‘upper_left’, ‘upper_right’, ‘lower_left’, ‘lower_right’ (also allows None). This value will be overridden by the optional x_pos and y_pos keywords.
time (boolean, optional) – Whether or not to show the ds.current_time of the data output. Can be used solo or in conjunction with redshift parameter.
redshift (boolean, optional) – Whether or not to show the ds.current_time of the data output. Can be used solo or in conjunction with the time parameter.
time_format (string, optional) – This specifies the format of the time output assuming “time” is the number of time and “unit” is units of the time (e.g. ‘s’, ‘Myr’, etc.) The time can be specified to arbitrary precision according to printf formatting codes (defaults to .1f – a float with 1 digits after decimal). Example: “Age = {time:.2f} {units}”.
time_unit (string, optional) – time_unit must be a valid yt time unit (e.g. ‘s’, ‘min’, ‘hr’, ‘yr’, ‘Myr’, etc.)
redshift_format (string, optional) – This specifies the format of the redshift output. The redshift can be specified to arbitrary precision according to printf formatting codes (defaults to 0.2f – a float with 2 digits after decimal). Example: “REDSHIFT = {redshift:03.3g}”,
draw_inset_box (boolean, optional) – Whether or not an inset box should be included around the text If so, it uses the inset_box_args to set the matplotlib FancyBboxPatch object.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data”: 3D dataset coordinates
”plot”: 2D coordinates defined by the actual plot limits
”axis”: MPL axis coordinates: (0,0) is lower left; (1,1) is upper right
”figure”: MPL figure coordinates: (0,0) is lower left, (1,1) is upper right
time_offset (float, (value, unit) tuple, or YTQuantity, optional) – Apply an offset to the time shown in the annotation from the value of the current time. If a scalar value with no units is passed in, the value of the time_unit kwarg is used for the units. Default: None, meaning no offset.
text_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib text object. Defaults:
{'color':'white', 'horizontalalignment':'center', 'verticalalignment':'top'}
.inset_box_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib FancyBboxPatch object as the inset box around the text. Defaults:
{'boxstyle':'square', 'pad':0.3, 'facecolor':'black', 'linewidth':3, 'edgecolor':'white', 'alpha':0.5}
Example
>>> import yt >>> ds = yt.load("Enzo_64/DD0020/data0020") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_timestamp()
- annotate_title(title)¶
Accepts a title and adds it to the plot
- annotate_triangle_facets(triangle_vertices, *, plot_args=None, **kwargs)¶
Intended for representing a slice of a triangular faceted geometry in a slice plot.
Uses a set of triangle_vertices to find all triangles the plane of a SlicePlot intersects with. The lines between the intersection points of the triangles are then added to the plot to create an outline of the geometry represented by the triangles.
- annotate_velocity(factor: tuple[int, int] | int = 16, *, scale=None, scale_units=None, normalize=False, plot_args=None, **kwargs)¶
Adds a ‘quiver’ plot of velocity to the plot, skipping all but every factor datapoint. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the velocity fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- property bounds¶
- clear_annotations(index: int | None = None)¶
Clear callbacks from the plot. If index is not set, clear all callbacks. If index is set, clear that index (ie 0 is the first one created, 1 is the 2nd one created, -1 is the last one created, etc.)
- display(name=None, mpl_kwargs=None)¶
Will attempt to show the plot in in an IPython notebook. Failing that, the plot will be saved to disk.
- export_to_mpl_figure(nrows_ncols, axes_pad=1.0, label_mode='L', cbar_location='right', cbar_size='5%', cbar_mode='each', cbar_pad='0%')¶
Creates a matplotlib figure object with the specified axes arrangement, nrows_ncols, and maps the underlying figures to the matplotlib axes. Note that all of these parameters are fed directly to the matplotlib ImageGrid class to create the new figure layout.
- Parameters:
nrows_ncols (tuple) – the number of rows and columns of the axis grid (e.g., nrows_ncols=(2,2,))
axes_pad (float) – padding between axes in inches
label_mode (one of "L", "1", "all") – arrangement of axes that are labeled
cbar_location (one of "left", "right", "bottom", "top") – where to place the colorbar
cbar_size (string (percentage)) – scaling of the colorbar (e.g., “5%”)
cbar_mode (one of "each", "single", "edge", None) – how to represent the colorbar
cbar_pad (string (percentage)) – padding between the axis and colorbar (e.g. “5%”)
- Return type:
The return is a matplotlib figure object.
Examples
>>> import yt >>> ds = yt.load_sample("IsolatedGalaxy") >>> fields = ["density", "velocity_x", "velocity_y", "velocity_magnitude"] >>> p = yt.SlicePlot(ds, "z", fields) >>> p.set_log("velocity_x", False) >>> p.set_log("velocity_y", False) >>> fig = p.export_to_mpl_figure((2, 2)) >>> fig.tight_layout() >>> fig.savefig("test.png")
- flip_horizontal()¶
inverts the horizontal axis (the image’s abscissa)
- flip_vertical()¶
inverts the vertical axis (the image’s ordinate)
- property frb¶
- get_log(field)¶
get the transform type of a field.
- Parameters:
field (string) – the field to get a transform if field == ‘all’, applies to all plots.
- hide_axes(field=None, draw_frame=None)¶
Hides the axes for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object.
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to hide the axes.
draw_frame (boolean) – If True, the axes frame will still be drawn. Defaults to False. See note below for more details.
Examples
This will save an image with no axes.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.save()
This will save an image with no axis or colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.hide_colorbar() >>> s.save()
Note
By default, when removing the axes, the patch on which the axes are drawn is disabled, making it impossible to later change e.g. the background colour. To force the axes patch to be displayed while still hiding the axes, set the
draw_frame
keyword argument toTrue
.
- hide_colorbar(field=None)¶
Hides the colorbar for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object.
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to hide the colorbar. If None or ‘all’ is provided, will default to using all fields available for this object.
Examples
This will save an image with no colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_colorbar() >>> s.save()
This will save an image with no axis or colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.hide_colorbar() >>> s.save()
- list_annotations()¶
List the current callbacks for the plot, along with their index. This index can be used with clear_annotations to remove a callback from the current plot.
- pan(deltas)¶
Pan the image by specifying absolute code unit coordinate deltas.
- Parameters:
deltas (Two-element sequence of floats, quantities, or (float, unit)) –
tuples.
(delta_x, delta_y). If a unit is not supplied the unit is assumed to be code_length.
- pan_rel(deltas)¶
Pan the image by specifying relative deltas, to the FOV.
- Parameters:
deltas (sequence of floats) – (delta_x, delta_y) in relative code unit coordinates
- piter(*args, **kwargs)¶
- refresh()¶
- render() None ¶
Render plots. This operation is expensive and usually doesn’t need to be requested explicitly. In most cases, yt handles rendering automatically and delays it as much as possible to avoid redundant calls on each plot modification (e.g. via annotate_* methods).
However, valid use cases of this method include: - fine control of render (and clear) operations when yt plots are combined with plot
customizations other than plot callbacks (annotate_*)
testing
- run_callbacks()¶
- static sanitize_normal_vector(ds, normal) str | ndarray ¶
Return the name of a cartesian axis whener possible, or a 3-element 1D ndarray of float64 in any other valid case. Fail with a descriptive error message otherwise.
- save(name: str | list[str] | tuple[str, ...] | None = None, suffix: str | None = None, mpl_kwargs: dict[str, Any] | None = None)¶
saves the plot to disk.
- Parameters:
name (string or tuple, optional) – The base of the filename. If name is a directory or if name is not set, the filename of the dataset is used. For a tuple, the resulting path will be given by joining the elements of the tuple
suffix (string, optional) – Specify the image type by its suffix. If not specified, the output type will be inferred from the filename. Defaults to ‘.png’.
mpl_kwargs (dict, optional) – A dict of keyword arguments to be passed to matplotlib.
slc.save(mpl_kwargs={"bbox_inches" (>>>)
- set_antialias(aa)¶
Turn antialiasing on or off.
- Parameters:
aa (boolean)
- set_axes_unit(unit_name)¶
Set the unit for display on the x and y axes of the image.
- Parameters:
unit_name (string or two element tuple of strings) – A unit, available for conversion in the dataset, that the image extents will be displayed in. If set to None, any previous units will be reset. If the unit is None, the default is chosen. If unit_name is ‘1’, ‘u’, or ‘unitary’, it will not display the units, and only show the axes name. If unit_name is a tuple, the first element is assumed to be the unit for the x axis and the second element the unit for the y axis.
- Raises:
YTUnitNotRecognized – If the unit is not known, this will be raised.
Examples
>>> from yt import load >>> ds = load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> p = ProjectionPlot(ds, "y", "Density") >>> p.set_axes_unit("kpc")
- set_background_color(field, color=None)¶
set the background color to match provided color
- Parameters:
field (string) – the field to set the colormap if field == ‘all’, applies to all plots.
color (string or RGBA tuple (optional)) – if set, set the background color to this color if unset, background color is set to the bottom value of the color map
- set_buff_size(size)¶
Sets a new buffer size for the fixed resolution buffer
- Parameters:
size (int or two element sequence of ints) – The number of data elements in the buffer on the x and y axes. If a scalar is provided, then the buffer is assumed to be square.
- set_center(new_center, unit='code_length')¶
Sets a new center for the plot window
- Parameters:
new_center (two element sequence of floats) – The coordinates of the new center of the image in the coordinate system defined by the plot axes. If the unit keyword is not specified, the coordinates are assumed to be in code units.
unit (string) – The name of the unit new_center is given in. If new_center is a YTArray or tuple of YTQuantities, this keyword is ignored.
- set_cmap(field, cmap)¶
set the colormap for one of the fields
- Parameters:
field (string) – the field to set the colormap if field == ‘all’, applies to all plots.
cmap (string or tuple) – If a string, will be interpreted as name of the colormap. If a tuple, it is assumed to be of the form (name, type, number) to be used for palettable functionality. (name, type, number, bool) can be used to specify if a reverse colormap is to be used.
- set_colorbar_label(field, label)¶
Sets the colorbar label.
- set_colorbar_minorticks(field, state)¶
turn colorbar minor ticks on or off in the current plot
Displaying minor ticks reduces performance; turn them off using set_colorbar_minorticks(‘all’, False) if drawing speed is a problem.
- Parameters:
field (string) – the field to remove colorbar minorticks if field == ‘all’, applies to all plots.
state (bool) – the state indicating ‘on’ (True) or ‘off’ (False)
- set_figure_size(size)¶
Sets a new figure size for the plot
- Parameters:
size (float, a sequence of two floats, or None) – The size of the figure (in units of inches), including the margins but not the colorbar. If a single float is passed, it’s interpreted as the size along the long axis. Pass None to reset
- set_font(font_dict=None)¶
Set the font and font properties.
- Parameters:
font_dict (dict) –
A dict of keyword parameters to be passed to
matplotlib.font_manager.FontProperties
.Possible keys include:
family - The font family. Can be serif, sans-serif, cursive, ‘fantasy’ or ‘monospace’.
style - The font style. Either normal, italic or oblique.
color - A valid color string like ‘r’, ‘g’, ‘red’, ‘cobalt’, and ‘orange’.
variant - Either normal or small-caps.
size - Either a relative value of xx-small, x-small, small, medium, large, x-large, xx-large or an absolute font size, e.g. 12
stretch - A numeric value in the range 0-1000 or one of ultra-condensed, extra-condensed, condensed, semi-condensed, normal, semi-expanded, expanded, extra-expanded or ultra-expanded
weight - A numeric value in the range 0-1000 or one of ultralight, light, normal, regular, book, medium, roman, semibold, demibold, demi, bold, heavy, extra bold, or black
See the matplotlib font manager API documentation for more details. https://matplotlib.org/stable/api/font_manager_api.html
Notes
Mathtext axis labels will only obey the size and color keyword.
Examples
This sets the font to be 24-pt, blue, sans-serif, italic, and bold-face.
>>> slc = SlicePlot(ds, "x", "Density") >>> slc.set_font( ... { ... "family": "sans-serif", ... "style": "italic", ... "weight": "bold", ... "size": 24, ... "color": "blue", ... } ... )
- set_font_size(size)¶
Set the size of the font used in the plot
This sets the font size by calling the set_font function. See set_font for more font customization options.
- Parameters:
size (float)
inch). (The absolute size of the font in points (1 pt = 1/72)
- set_log(field, log: bool | None = None, *, linthresh: float | unyt_quantity | tuple[float, Unit | str] | Literal['auto'] | None = None, symlog_auto: bool | None = None)¶
set a field to log, linear, or symlog.
Symlog scaling is a combination of linear and log, where from 0 to a threshold value, it operates as linear, and then beyond that it operates as log. Symlog can also work with negative values in log space as well as negative and positive values simultaneously and symmetrically. If symlog scaling is desired, please set log=True and either set symlog_auto=True or select a value for linthresh.
- Parameters:
field (string) – the field to set a transform if field == ‘all’, applies to all plots.
log (boolean, optional) – set log to True for log scaling, False for linear scaling.
linthresh (float, (float, str), unyt_quantity, or 'auto', optional) – when using symlog scaling, linthresh is the value at which scaling transitions from linear to logarithmic. linthresh must be positive. Note: setting linthresh will automatically enable symlog scale
arguments (Note that log and linthresh are mutually exclusive)
- set_minorticks(field, state)¶
Turn minor ticks on or off in the current plot.
Displaying minor ticks reduces performance; turn them off using set_minorticks(‘all’, False) if drawing speed is a problem.
- Parameters:
field (string) – the field to remove minorticks if field == ‘all’, applies to all plots.
state (bool) – the state indicating ‘on’ (True) or ‘off’ (False)
- set_mpl_projection(mpl_proj)¶
Set the matplotlib projection type with a cartopy transform function
Given a string or a tuple argument, this will project the data onto the plot axes with the chosen transform function.
Assumes that the underlying data has a PlateCarree transform type.
To annotate the plot with coastlines or other annotations, render() will need to be called after this function to make the axes available for annotation.
- Parameters:
mpl_proj (string or tuple) – if passed as a string, mpl_proj is the specified projection type, if passed as a tuple, then tuple will take the form of
("ProjectionType", (args))
or("ProjectionType", (args), {kwargs})
Valid projection type options include: ‘PlateCarree’, ‘LambertConformal’, ‘LabmbertCylindrical’, ‘Mercator’, ‘Miller’, ‘Mollweide’, ‘Orthographic’, ‘Robinson’, ‘Stereographic’, ‘TransverseMercator’, ‘InterruptedGoodeHomolosine’, ‘RotatedPole’, ‘OGSB’, ‘EuroPP’, ‘Geostationary’, ‘Gnomonic’, ‘NorthPolarStereo’, ‘OSNI’, ‘SouthPolarStereo’, ‘AlbersEqualArea’, ‘AzimuthalEquidistant’, ‘Sinusoidal’, ‘UTM’, ‘NearsidePerspective’, ‘LambertAzimuthalEqualArea’
Examples
This will create a Mollweide projection using Mollweide default values and annotate it with coastlines
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection("AIRDENS", "Mollweide") >>> p.render() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will move the PlateCarree central longitude to 90 degrees and annotate with coastlines.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection( ... "AIRDENS", ("PlateCarree", (), {"central_longitude": 90, "globe": None}) ... ) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will create a RoatatedPole projection with the unrotated pole position at 37.5 degrees latitude and 177.5 degrees longitude by passing them in as args.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection("RotatedPole", (177.5, 37.5)) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will create a RoatatedPole projection with the unrotated pole position at 37.5 degrees latitude and 177.5 degrees longitude by passing them in as kwargs.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection( ... ("RotatedPole", (), {"pole_latitude": 37.5, "pole_longitude": 177.5}) ... ) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
- set_norm(field, norm: Normalize)¶
Set a custom
matplotlib.colors.Normalize
to plot field.Any constraints previously set with set_log, set_zlim will be dropped.
Note that any float value attached to norm (e.g. vmin, vmax, vcenter …) will be read in the current displayed units, which can be controlled with the set_unit method.
- Parameters:
field (str or tuple[str, str]) – if field == ‘all’, applies to all plots.
norm (matplotlib.colors.Normalize) – see https://matplotlib.org/stable/tutorials/colors/colormapnorms.html
- set_origin(origin)¶
Set the plot origin.
- Parameters:
origin (string or length 1, 2, or 3 sequence.) – The location of the origin of the plot coordinate system. This is typically represented by a ‘-’ separated string or a tuple of strings. In the first index the y-location is given by ‘lower’, ‘upper’, or ‘center’. The second index is the x-location, given as ‘left’, ‘right’, or ‘center’. Finally, whether the origin is applied in ‘domain’ space, plot ‘window’ space or ‘native’ simulation coordinate system is given. For example, both ‘upper-right-domain’ and [‘upper’, ‘right’, ‘domain’] place the origin in the upper right hand corner of domain space. If x or y are not given, a value is inferred. For instance, ‘left-domain’ corresponds to the lower-left hand corner of the simulation domain, ‘center-domain’ corresponds to the center of the simulation domain, or ‘center-window’ for the center of the plot window. In the event that none of these options place the origin in a desired location, a sequence of tuples and a string specifying the coordinate space can be given. If plain numeric types are input, units of code_length are assumed. Further examples:
=============================== (===============================================)
example (format)
===============================
'domain' ('{space}')
'left-window' ('{xloc}-{space}')
'upper-domain' ('{yloc}-{space}')
'lower-right-window' ('{yloc}-{xloc}-{space}')
('{space}'
('window' ())
)
('{xloc}'
('right' ('{space}'))
'domain')
('{yloc}'
('lower' ('{space}'))
'window')
('{yloc}'
'{xloc}'
('lower'
'right'
'window')
((yloc
'{unit}')
(xloc
'{unit}')
((0 ('{space}'))
'm')
(.4
'm')
'window')
(xloc
yloc
(0.23 ('{space}'))
0.5
'domain')
===============================
- set_unit(field, new_unit, equivalency=None, equivalency_kwargs=None)¶
Sets a new unit for the requested field
- Parameters:
field (string or field tuple) – The name of the field that is to be changed.
new_unit (string or Unit object)
equivalency (string, optional) – If set, the equivalency to use to convert the current units to the new requested unit. If None, the unit conversion will be done without an equivalency
equivalency_kwargs (string, optional) – Keyword arguments to be passed to the equivalency. Only used if
equivalency
is set.
- set_width(width, unit=None)¶
set the width of the plot window
- Parameters:
width (float, array of floats, (float, unit) tuple, or tuple of) –
(float, unit) tuples.
Width can have four different formats to support windows with variable x and y widths. They are:
format
example
(float, string)
(10,’kpc’)
((float, string), (float, string))
((10,’kpc’),(15,’kpc’))
float
0.2
(float, float)
(0.2, 0.3)
For example, (10, ‘kpc’) requests a plot window that is 10 kiloparsecs wide in the x and y directions, ((10,’kpc’),(15,’kpc’)) requests a window that is 10 kiloparsecs wide along the x axis and 15 kiloparsecs wide along the y axis. In the other two examples, code units are assumed, for example (0.2, 0.3) requests a plot that has an x width of 0.2 and a y width of 0.3 in code units. If units are provided the resulting plot axis labels will use the supplied units.
unit (str) – the unit the width has been specified in. If width is a tuple, this argument is ignored. Defaults to code units.
- set_xlabel(label)¶
Allow the user to modify the X-axis title Defaults to the global value. Fontsize defaults to 18.
- Parameters:
label (str) – The new string for the x-axis.
(cm$^{-3}$)") (>>> plot.set_xlabel("H2I Number Density)
- set_ylabel(label)¶
Allow the user to modify the Y-axis title Defaults to the global value.
- Parameters:
label (str) – The new string for the y-axis.
(K)") (>>> plot.set_ylabel("Temperature)
- set_zlim(field, zmin: ~unyt.array.unyt_quantity | tuple[float, ~unyt.unit_object.Unit | str] | float | ~typing.Literal['min'] | ~yt.visualization.plot_container.Unset = <yt.visualization.plot_container.Unset object>, zmax: ~unyt.array.unyt_quantity | tuple[float, ~unyt.unit_object.Unit | str] | float | ~typing.Literal['max'] | ~yt.visualization.plot_container.Unset = <yt.visualization.plot_container.Unset object>, dynamic_range: float | None = None)¶
set the scale of the colormap
- Parameters:
field (string) – the field to set a colormap scale if field == ‘all’, applies to all plots.
zmin (float, Quantity, or 'min') – the new minimum of the colormap scale. If ‘min’, will set to the minimum value in the current view.
zmax (float, Quantity, or 'max') – the new maximum of the colormap scale. If ‘max’, will set to the maximum value in the current view.
dynamic_range (float (default: None)) – The dynamic range of the image. If zmin == None, will set zmin = zmax / dynamic_range If zmax == None, will set zmax = zmin * dynamic_range
- setup_callbacks()¶
- show()¶
This will send any existing plots to the IPython notebook.
If yt is being run from within an IPython session, and it is able to determine this, this function will send any existing plots to the notebook for display.
If yt can’t determine if it’s inside an IPython session, it will raise YTNotInsideNotebook.
Examples
>>> from yt import SlicePlot >>> slc = SlicePlot( ... ds, "x", [("gas", "density"), ("gas", "velocity_magnitude")] ... ) >>> slc.show()
- show_axes(field=None)¶
Shows the axes for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object. See hide_axes().
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to show the axes.
- show_colorbar(field=None)¶
Shows the colorbar for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object. See hide_colorbar().
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional))
colorbar. (The name of the field(s) that we want to show the)
- swap_axes()¶
- to_fits_data(fields=None, other_keys=None, length_unit=None, **kwargs)¶
Export the fields in this PlotWindow instance to a FITSImageData instance.
This will export a set of FITS images of either the fields specified or all the fields already in the object.
- Parameters:
fields (list of strings) – These fields will be pixelized and output. If “None”, the keys of the FRB will be used.
other_keys (dictionary, optional) – A set of header keys and values to write into the FITS header.
length_unit (string, optional) – the length units that the coordinates are written in. The default is to use the default length unit of the dataset.
- property width¶
- class yt.visualization.plot_window.AxisAlignedSlicePlot(ds, normal, fields, *args, **kwargs)[source]¶
Bases:
SlicePlot
,PWViewerMPL
Creates a slice plot from a dataset
Given a ds object, an axis to slice along, and a field name string, this will return a PWViewerMPL object containing the plot.
The plot can be updated using one of the many helper functions defined in PlotWindow.
- Parameters:
ds (Dataset) – This is the dataset object corresponding to the simulation output to be plotted.
normal (int or one of 'x', 'y', 'z') – An int corresponding to the axis to slice along (0=x, 1=y, 2=z) or the axis name itself
fields (string) – The name of the field(s) to be plotted.
center ('center', 'c', 'left', 'l', 'right', 'r', id of a global extremum, or array-like) –
The coordinate of the selection’s center. Defaults to the ‘center’, i.e. center of the domain.
Centering on the min or max of a field is supported by passing a tuple such as (‘min’, (‘gas’, ‘density’)) or (‘max’, (‘gas’, ‘temperature’). A single string may also be used (e.g. “min_density” or “max_temperature”), though it’s not as flexible and does not allow to select an exact field/particle type. With this syntax, the first field matching the provided name is selected. ‘max’ or ‘m’ can be used as a shortcut for (‘max’, (‘gas’, ‘density’)) ‘min’ can be used as a shortcut for (‘min’, (‘gas’, ‘density’))
One can also select an exact point as a 3 element coordinate sequence, e.g. [0.5, 0.5, 0] Units can be specified by passing in center as a tuple containing a 3-element coordinate sequence and string unit name, e.g. ([0, 0.5, 0.5], “cm”), or by passing in a YTArray. Code units are assumed if unspecified.
The domain edges along the selected axis can be selected with ‘left’/’l’ and ‘right’/’r’ respectively.
width (tuple or a float.) –
Width can have four different formats to support windows with variable x and y widths. They are:
format
example
(float, string)
(10,’kpc’)
((float, string), (float, string))
((10,’kpc’),(15,’kpc’))
float
0.2
(float, float)
(0.2, 0.3)
For example, (10, ‘kpc’) requests a plot window that is 10 kiloparsecs wide in the x and y directions, ((10,’kpc’),(15,’kpc’)) requests a window that is 10 kiloparsecs wide along the x axis and 15 kiloparsecs wide along the y axis. In the other two examples, code units are assumed, for example (0.2, 0.3) requests a plot that has an x width of 0.2 and a y width of 0.3 in code units. If units are provided the resulting plot axis labels will use the supplied units.
origin (string or length 1, 2, or 3 sequence.) –
The location of the origin of the plot coordinate system. This is typically represented by a ‘-’ separated string or a tuple of strings. In the first index the y-location is given by ‘lower’, ‘upper’, or ‘center’. The second index is the x-location, given as ‘left’, ‘right’, or ‘center’. Finally, whether the origin is applied in ‘domain’ space, plot ‘window’ space or ‘native’ simulation coordinate system is given. For example, both ‘upper-right-domain’ and [‘upper’, ‘right’, ‘domain’] place the origin in the upper right hand corner of domain space. If x or y are not given, a value is inferred. For instance, ‘left-domain’ corresponds to the lower-left hand corner of the simulation domain, ‘center-domain’ corresponds to the center of the simulation domain, or ‘center-window’ for the center of the plot window. In the event that none of these options place the origin in a desired location, a sequence of tuples and a string specifying the coordinate space can be given. If plain numeric types are input, units of code_length are assumed. Further examples:
format
example
’{space}’
’domain’
’{xloc}-{space}’
’left-window’
’{yloc}-{space}’
’upper-domain’
’{yloc}-{xloc}-{space}’
’lower-right-window’
(‘{space}’,)
(‘window’,)
(‘{xloc}’, ‘{space}’)
(‘right’, ‘domain’)
(‘{yloc}’, ‘{space}’)
(‘lower’, ‘window’)
(‘{yloc}’, ‘{xloc}’, ‘{space}’)
(‘lower’, ‘right’, ‘window’)
((yloc, ‘{unit}’), (xloc, ‘{unit}’), ‘{space}’)
((0, ‘m’), (.4, ‘m’), ‘window’)
(xloc, yloc, ‘{space}’)
(0.23, 0.5, ‘domain’)
axes_unit (string) – The name of the unit for the tick labels on the x and y axes. Defaults to None, which automatically picks an appropriate unit. If axes_unit is ‘1’, ‘u’, or ‘unitary’, it will not display the units, and only show the axes name.
fontsize (integer) – The size of the fonts for the axis, colorbar, and tick labels.
field_parameters (dictionary) – A dictionary of field parameters than can be accessed by derived fields.
data_source (YTSelectionContainer object) – Object to be used for data selection. Defaults to ds.all_data(), a region covering the full domain
buff_size (length 2 sequence) – Size of the buffer to use for the image, i.e. the number of resolution elements used. Effectively sets a resolution limit to the image if buff_size is smaller than the finest gridding.
Examples
This will save an image in the file ‘sliceplot_Density.png’
>>> from yt import load >>> ds = load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> p = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> p.save("sliceplot")
- annotate_arrow(pos, *, length=0.03, width=0.0001, head_width=0.01, head_length=0.01, starting_pos=None, coord_system='data', plot_args: dict[str, Any] | None = None, **kwargs)¶
Overplot arrow(s) pointing at position(s) for highlighting specific features. By default, arrow points from lower left to the designated position “pos” with arrow length “length”. Alternatively, if “starting_pos” is set, arrow will stretch from “starting_pos” to “pos” and “length” will be disregarded.
“coord_system” keyword refers to positions set in “pos” arg and “starting_pos” keyword, which by default are in data coordinates.
“length”, “width”, “head_length”, and “head_width” keywords for the arrow are all in axis units, ie relative to the size of the plot axes as 1, even if the position of the arrow is set relative to another coordinate system.
- Parameters:
pos (array-like) – These are the coordinates where the marker(s) will be overplotted Either as [x,y,z] or as [[x1,x2,…],[y1,y2,…],[z1,z2,…]]
length (float, optional) – The length, in axis units, of the arrow. Default: 0.03
width (float, optional) – The width, in axis units, of the tail line of the arrow. Default: 0.003
head_length (float, optional) – The length, in axis units, of the head of the arrow. If set to None, use 1.5*head_width Default: None
head_width (float, optional) – The width, in axis units, of the head of the arrow. Default: 0.02
starting_pos (2- or 3-element tuple, list, or array, optional) – These are the coordinates from which the arrow starts towards its point. Not compatible with ‘length’ kwarg.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
plot_args (dictionary, optional) – This dictionary is passed to the MPL arrow function for generating the arrow. By default, it is: {‘color’:’white’}
Examples
>>> # Overplot an arrow pointing to feature at data coord: (0.2, 0.3, 0.4) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_arrow([0.2, 0.3, 0.4]) >>> s.save()
>>> # Overplot a red arrow with longer length pointing to plot coordinate >>> # (0.1, -0.1) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_arrow( ... [0.1, -0.1], length=0.06, coord_system="plot", color="red" ... ) >>> s.save()
- annotate_cell_edges(line_width=0.002, alpha=1.0, color='black')¶
Annotate cell edges. This is done through a second call to pixelize, where the distance from a pixel to a cell boundary in pixels is compared against the line_width argument. The secondary image is colored as color and overlaid with the alpha value.
- Parameters:
line_width (float) – The width of the cell edge lines in normalized units relative to the size of the longest axis. Default is 1% of the size of the smallest axis.
alpha (float) – When the second image is overlaid, it will have this level of alpha transparency. Default is 1.0 (fully-opaque).
color (tuple of three floats or matplotlib color name) – This is the color of the cell edge values. It defaults to black.
Examples
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_cell_edges() >>> s.save()
- annotate_clumps(clumps, *, plot_args=None, **kwargs)¶
Take a list of clumps and plot them as a set of contours.
- annotate_contour(field: tuple[str, str] | str, levels: int = 5, *, factor: tuple[int, int] | int = 4, clim: tuple[float, float] | None = None, label: bool = False, take_log: bool | None = None, data_source: YTDataContainer | None = None, plot_args: dict[str, Any] | None = None, text_args: dict[str, Any] | None = None, ncont: int | None = None) None ¶
Add contours in field to the plot. levels governs the number of contours generated, factor governs the number of points used in the interpolation, take_log governs how it is contoured and clim gives the (lower, upper) limits for contouring. An alternate data source can be specified with data_source, but by default the plot’s data source will be queried.
- annotate_cquiver(field_x, field_y, field_c=None, *, factor: tuple[int, int] | int = 16, scale=None, scale_units=None, normalize=False, plot_args=None, **kwargs)¶
Get a quiver plot on top of a cutting plane, using field_x and field_y, skipping every factor datapoint in the discretization. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- annotate_grids(alpha=0.7, min_pix=1, min_pix_ids=20, draw_ids=False, id_loc=None, periodic=True, min_level=None, max_level=None, cmap='B-W LINEAR_r', edgecolors=None, linewidth=1.0)¶
Draws grids on an existing PlotWindow object. Adds grid boundaries to a plot, optionally with alpha-blending. By default, colors different levels of grids with different colors going from white to black, but you can change to any arbitrary colormap with cmap keyword, to all black grid edges for all levels with cmap=None and edgecolors=None, or to an arbitrary single color for grid edges with edgecolors=’YourChosenColor’ defined in any of the standard ways (e.g., edgecolors=’white’, edgecolors=’r’, edgecolors=’#00FFFF’, or edgecolor=’0.3’, where the last is a float in 0-1 scale indicating gray). Note that setting edgecolors overrides cmap if you have both set to non-None values. Cutoff for display is at min_pix wide. draw_ids puts the grid id a the corner of the grid (but its not so great in projections…). id_loc determines which corner holds the grid id. One can set min and maximum level of grids to display, and can change the linewidth of the displayed grids.
- annotate_line(p1, p2, *, coord_system='data', plot_args: dict[str, Any] | None = None, **kwargs)¶
Overplot a line with endpoints at p1 and p2. p1 and p2 should be 2D or 3D coordinates consistent with the coordinate system denoted in the “coord_system” keyword.
- Parameters:
p1 (2- or 3-element tuples, lists, or arrays) – These are the coordinates of the endpoints of the line.
p2 (2- or 3-element tuples, lists, or arrays) – These are the coordinates of the endpoints of the line.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates p1 and p2. Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
plot_args (dictionary, optional) – This dictionary is passed to the MPL plot function for generating the line. By default, it is: {‘color’:’white’, ‘linewidth’:2}
Examples
>>> # Overplot a diagonal white line from the lower left corner to upper >>> # right corner >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_line([0, 0], [1, 1], coord_system="axis") >>> s.save()
>>> # Overplot a red dashed line from data coordinate (0.1, 0.2, 0.3) to >>> # (0.5, 0.6, 0.7) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_line( ... [0.1, 0.2, 0.3], ... [0.5, 0.6, 0.7], ... coord_system="data", ... color="red", ... linestyles="--", ... ) >>> s.save()
- annotate_line_integral_convolution(field_x, field_y, texture=None, kernellen=50.0, lim=(0.5, 0.6), cmap='binary', alpha=0.8, const_alpha=False)¶
Add the line integral convolution to the plot for vector fields visualization. Two component of vector fields needed to be provided (i.e., velocity_x and velocity_y, magnetic_field_x and magnetic_field_y).
- Parameters:
field_x (string) – The names of two components of vector field which will be visualized
field_y (string) – The names of two components of vector field which will be visualized
texture (2-d array with the same shape of image, optional) – Texture will be convolved when computing line integral convolution. A white noise background will be used as default.
kernellen (float, optional) – The lens of kernel for convolution, which is the length over which the convolution will be performed. For longer kernellen, longer streamline structure will appear.
lim (2-element tuple, list, or array, optional) – The value of line integral convolution will be clipped to the range of lim, which applies upper and lower bounds to the values of line integral convolution and enhance the visibility of plots. Each element should be in the range of [0,1].
cmap (string, optional) – The name of colormap for line integral convolution plot.
alpha (float, optional) – The alpha value for line integral convolution plot.
const_alpha (boolean, optional) – If set to False (by default), alpha will be weighted spatially by the values of line integral convolution; otherwise a constant value of the given alpha is used.
Example
>>> import yt >>> ds = yt.load("Enzo_64/DD0020/data0020") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_line_integral_convolution( ... "velocity_x", "velocity_y", lim=(0.5, 0.65) ... )
- annotate_magnetic_field(factor: tuple[int, int] | int = 16, *, scale=None, scale_units=None, normalize=False, plot_args=None, **kwargs)¶
Adds a ‘quiver’ plot of magnetic field to the plot, skipping all but every factor datapoint. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the magnetic fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- annotate_marker(pos, marker='x', *, coord_system='data', plot_args=None, **kwargs)¶
Overplot marker(s) at a position(s) for highlighting specific features.
- Parameters:
pos (array-like) – These are the coordinates where the marker(s) will be overplotted Either as [x,y,z] or as [[x1,x2,…],[y1,y2,…],[z1,z2,…]]
marker (string, optional) – The shape of the marker to be passed to the MPL scatter function. By default, it is ‘x’, but other acceptable values are: ‘.’, ‘o’, ‘v’, ‘^’, ‘s’, ‘p’ ‘*’, etc. See matplotlib.markers for more information.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
plot_args (dictionary, optional) – This dictionary is passed to the MPL scatter function for generating the marker. By default, it is: {‘color’:’white’, ‘s’:50}
Examples
>>> # Overplot a white X on a feature at data location (0.5, 0.5, 0.5) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_marker([0.4, 0.5, 0.6]) >>> s.save()
>>> # Overplot a big yellow circle at axis location (0.1, 0.2) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_marker( ... [0.1, 0.2], ... marker="o", ... coord_system="axis", ... color="yellow", ... s=200, ... ) >>> s.save()
- annotate_mesh_lines(*, plot_args=None, **kwargs)¶
Adds mesh lines to the plot. Only works for unstructured or semi-structured mesh data. For structured grid data, see GridBoundaryCallback or CellEdgesCallback.
- Parameters:
plot_args (dict, optional) – A dictionary of arguments that will be passed to matplotlib.
Example
>>> import yt >>> ds = yt.load("MOOSE_sample_data/out.e-s010") >>> sl = yt.SlicePlot(ds, "z", ("connect2", "convected")) >>> sl.annotate_mesh_lines(color="black")
- annotate_particles(width, p_size=1.0, col='k', marker='o', stride=1, ptype='all', alpha=1.0, data_source=None)¶
Adds particle positions, based on a thick slab along axis with a width along the line of sight. p_size controls the number of pixels per particle, and col governs the color. ptype will restrict plotted particles to only those that are of a given type. alpha determines the opacity of the marker symbol used in the scatter. An alternate data source can be specified with data_source, but by default the plot’s data source will be queried.
- annotate_quiver(field_x, field_y, field_c=None, *, factor: tuple[int, int] | int = 16, scale=None, scale_units=None, normalize=False, bv_x=0, bv_y=0, plot_args=None, **kwargs)¶
Adds a ‘quiver’ plot to any plot, using the field_x and field_y from the associated data, skipping every factor pixels. field_c is an optional field name used for color. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- annotate_ray(ray, *, arrow=False, plot_args=None, **kwargs)¶
Adds a line representing the projected path of a ray across the plot. The ray can be either a YTOrthoRay, YTRay, or a LightRay object. annotate_ray() will properly account for periodic rays across the volume. If arrow is set to True, uses the MPL.pyplot.arrow function, otherwise uses the MPL.pyplot.plot function to plot a normal line. Adjust plot_args accordingly.
- Parameters:
ray (YTOrthoRay, YTRay, or LightRay) – Ray is the object that we want to include. We overplot the projected trajectory of the ray. If the object is a trident.LightRay object, it will only plot the segment of the LightRay that intersects the dataset currently displayed.
arrow (boolean, optional) – Whether or not to place an arrowhead on the front of the ray to denote direction Default: False
plot_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib line object. Defaults: {‘color’:’white’, ‘linewidth’:2}.
Examples
>>> # Overplot a ray and an ortho_ray object on a projection >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> oray = ds.ortho_ray(1, (0.3, 0.4)) # orthoray down the y axis >>> ray = ds.ray((0.1, 0.2, 0.3), (0.6, 0.7, 0.8)) # arbitrary ray >>> p = yt.ProjectionPlot(ds, "z", "density") >>> p.annotate_ray(oray) >>> p.annotate_ray(ray) >>> p.save()
>>> # Overplot a LightRay object on a projection >>> import yt >>> from trident import LightRay >>> ds = yt.load("enzo_cosmology_plus/RD0004/RD0004") >>> lr = LightRay( ... "enzo_cosmology_plus/AMRCosmology.enzo", "Enzo", 0.0, 0.1, time_data=False ... ) >>> lray = lr.make_light_ray(seed=1) >>> p = yt.ProjectionPlot(ds, "z", "density") >>> p.annotate_ray(lr) >>> p.save()
- annotate_scale(*, corner='lower_right', coeff=None, unit=None, pos=None, max_frac=0.16, min_frac=0.015, coord_system='axis', text_args=None, size_bar_args=None, draw_inset_box=False, inset_box_args=None, scale_text_format='{scale} {units}')¶
Annotates the scale of the plot at a specified location in the image (either in a preset corner, or by specifying (x,y) image coordinates with the pos argument. Coeff and units (e.g. 1 Mpc or 100 kpc) refer to the distance scale you desire to show on the plot. If no coeff and units are specified, an appropriate pair will be determined such that your scale bar is never smaller than min_frac or greater than max_frac of your plottable axis length. Additional customization of the scale bar is possible by adjusting the text_args and size_bar_args dictionaries. The text_args dictionary accepts matplotlib’s font_properties arguments to override the default font_properties for the current plot. The size_bar_args dictionary accepts keyword arguments for the AnchoredSizeBar class in matplotlib’s axes_grid toolkit.
- Parameters:
corner (string, optional) – Corner sets up one of 4 predeterimined locations for the scale bar to be displayed in the image: ‘upper_left’, ‘upper_right’, ‘lower_left’, ‘lower_right’ (also allows None). This value will be overridden by the optional ‘pos’ keyword.
coeff (float, optional) – The coefficient of the unit defining the distance scale (e.g. 10 kpc or 100 Mpc) for overplotting. If set to None along with unit keyword, coeff will be automatically determined to be a power of 10 relative to the best-fit unit.
unit (string, optional) – unit must be a valid yt distance unit (e.g. ‘m’, ‘km’, ‘AU’, ‘pc’, ‘kpc’, etc.) or set to None. If set to None, will be automatically determined to be the best-fit to the data.
pos (2- or 3-element tuples, lists, or arrays, optional) – The image location of the scale bar in the plot coordinate system. Setting pos overrides the corner parameter.
min_frac (float, optional) – The minimum/maximum fraction of the axis width for the scale bar to extend. A value of 1 would allow the scale bar to extend across the entire axis width. Only used for automatically calculating best-fit coeff and unit when neither is specified, otherwise disregarded.
max_frac (float, optional) – The minimum/maximum fraction of the axis width for the scale bar to extend. A value of 1 would allow the scale bar to extend across the entire axis width. Only used for automatically calculating best-fit coeff and unit when neither is specified, otherwise disregarded.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data”: 3D dataset coordinates
”plot”: 2D coordinates defined by the actual plot limits
”axis”: MPL axis coordinates: (0,0) is lower left; (1,1) is upper right
”figure”: MPL figure coordinates: (0,0) is lower left, (1,1) is upper right
text_args (dictionary, optional) – A dictionary of parameters to used to update the font_properties for the text in this callback. For any property not set, it will use the defaults of the plot. Thus one can modify the text size with
text_args={'size':24}
size_bar_args (dictionary, optional) – A dictionary of parameters to be passed to the Matplotlib AnchoredSizeBar initializer. Defaults:
{'pad': 0.25, 'sep': 5, 'borderpad': 1, 'color': 'w'}
draw_inset_box (boolean, optional) – Whether or not an inset box should be included around the scale bar.
inset_box_args (dictionary, optional) – A dictionary of keyword arguments to be passed to the matplotlib Patch object that represents the inset box. Defaults:
{'facecolor': 'black', 'linewidth': 3, 'edgecolor': 'white', 'alpha': 0.5, 'boxstyle': 'square'}
scale_text_format (string, optional) – This specifies the format of the scalebar value assuming “scale” is the numerical value and “unit” is units of the scale (e.g. ‘cm’, ‘kpc’, etc.) The scale can be specified to arbitrary precision according to printf formatting codes. The format string must only specify “scale” and “units”. Example: “Length = {scale:.2f} {units}”. Default: “{scale} {units}”
Example
>>> import yt >>> ds = yt.load("Enzo_64/DD0020/data0020") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_scale()
- annotate_sphere(center, radius, *, coord_system='data', text=None, circle_args=None, text_args=None)¶
Overplot a circle with designated center and radius with optional text.
- Parameters:
center (2- or 3-element tuple, list, or array) – These are the coordinates where the circle will be overplotted
radius (YTArray, float, or (1, ('kpc')) style tuple) – The radius of the circle in code coordinates
circle_args (dict, optional) – This dictionary is passed to the MPL circle object. By default, {‘color’:’white’}
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
text (string, optional) – Optional text to include next to the circle.
text_args (dictionary, optional) – This dictionary is passed to the MPL text function. By default, it is: {‘color’:’white’}
Examples
>>> # Overplot a white circle of radius 100 kpc over the central galaxy >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_sphere([0.5, 0.5, 0.5], radius=(100, "kpc")) >>> s.save()
- annotate_streamlines(field_x: tuple[str, str] | str, field_y: tuple[str, str] | str, *, linewidth: float | tuple[str, str] | str = 1.0, linewidth_upscaling: float = 1.0, color: Any | tuple[str, str] | None = None, color_threshold: float | unyt_quantity = -inf, factor: tuple[int, int] | int = 16, field_color=None, display_threshold=None, plot_args=None, **kwargs)¶
Plot streamlines using matplotlib.axes.Axes.streamplot
- Parameters:
field_x (field key) – The “velocity” analoguous field along the horizontal direction.
field_y (field key) – The “velocity” analoguous field along the vertical direction.
linewidth (float, or field key (default: 1.0)) – A constant scalar will be passed directly to matplotlib.axes.Axes.streamplot A field key will be first interpreted by yt and produce the adequate 2D array. Data fields are normalized by their maximum value, so the maximal linewidth is 1 by default. See linewidth_upscaling for fine tuning. Note that the absolute value is taken in all cases.
linewidth_upscaling (float (default: 1.0)) – A constant multiplicative factor applied to linewidth. Final linewidth is obtained as: linewidth_upscaling * abs(linewidth) / max(abs(linewidth))
color (a color identifier, or a field key (default: matplotlib.rcParams['line.color'])) – A constant color identifier will be passed directly to matplotlib.axes.Axes.streamplot A field key will be first interpreted by yt and produce the adequate 2D array. See https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.streamplot.html for how to customize color mapping using cmap and norm arguments.
color_threshold (float or unyt_quantity (default: -inf)) – Regions where the field used for color is lower than this threshold will be masked. Only used if color is a field key.
factor (int, or tuple[int, int] (default: 16)) – Fields are downed-sampled by this factor with respect to the background image buffer size. A single integer factor will be used for both direction, but a tuple of 2 integers can be passed to set x and y downsampling independently.
**kwargs (any additional keyword arguments will be passed) – directly to matplotlib.axes.Axes.streamplot
- annotate_text(pos, text, *, coord_system='data', text_args=None, inset_box_args=None)¶
Overplot text on the plot at a specified position. If you desire an inset box around your text, set one with the inset_box_args dictionary keyword.
- Parameters:
pos (2- or 3-element tuple, list, or array) – These are the coordinates where the text will be overplotted
text (string) – The text you wish to include
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
text_args (dictionary, optional) – This dictionary is passed to the MPL text function for generating the text. By default, it is: {‘color’:’white’} and uses the defaults for the other fonts in the image.
inset_box_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib FancyBboxPatch object as the inset box around the text. Default: {}
Examples
>>> # Overplot white text at data location [0.55, 0.7, 0.4] >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_text([0.55, 0.7, 0.4], "Here is a galaxy") >>> s.save()
>>> # Overplot yellow text at axis location [0.2, 0.8] with >>> # a shaded inset box >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_text( ... [0.2, 0.8], ... "Here is a galaxy", ... coord_system="axis", ... text_args={"color": "yellow"}, ... inset_box_args={ ... "boxstyle": "square,pad=0.3", ... "facecolor": "black", ... "linewidth": 3, ... "edgecolor": "white", ... "alpha": 0.5, ... }, ... ) >>> s.save()
- annotate_timestamp(x_pos=None, y_pos=None, corner='lower_left', *, time=True, redshift=False, time_format='t = {time:.1f} {units}', time_unit=None, redshift_format='z = {redshift:.2f}', draw_inset_box=False, coord_system='axis', time_offset=None, text_args=None, inset_box_args=None)¶
Annotates the timestamp and/or redshift of the data output at a specified location in the image (either in a present corner, or by specifying (x,y) image coordinates with the x_pos, y_pos arguments. If no time_units are specified, it will automatically choose appropriate units. It allows for custom formatting of the time and redshift information, as well as the specification of an inset box around the text.
- Parameters:
x_pos (floats, optional) – The image location of the timestamp in the coord system defined by the coord_system kwarg. Setting x_pos and y_pos overrides the corner parameter.
y_pos (floats, optional) – The image location of the timestamp in the coord system defined by the coord_system kwarg. Setting x_pos and y_pos overrides the corner parameter.
corner (string, optional) – Corner sets up one of 4 predeterimined locations for the timestamp to be displayed in the image: ‘upper_left’, ‘upper_right’, ‘lower_left’, ‘lower_right’ (also allows None). This value will be overridden by the optional x_pos and y_pos keywords.
time (boolean, optional) – Whether or not to show the ds.current_time of the data output. Can be used solo or in conjunction with redshift parameter.
redshift (boolean, optional) – Whether or not to show the ds.current_time of the data output. Can be used solo or in conjunction with the time parameter.
time_format (string, optional) – This specifies the format of the time output assuming “time” is the number of time and “unit” is units of the time (e.g. ‘s’, ‘Myr’, etc.) The time can be specified to arbitrary precision according to printf formatting codes (defaults to .1f – a float with 1 digits after decimal). Example: “Age = {time:.2f} {units}”.
time_unit (string, optional) – time_unit must be a valid yt time unit (e.g. ‘s’, ‘min’, ‘hr’, ‘yr’, ‘Myr’, etc.)
redshift_format (string, optional) – This specifies the format of the redshift output. The redshift can be specified to arbitrary precision according to printf formatting codes (defaults to 0.2f – a float with 2 digits after decimal). Example: “REDSHIFT = {redshift:03.3g}”,
draw_inset_box (boolean, optional) – Whether or not an inset box should be included around the text If so, it uses the inset_box_args to set the matplotlib FancyBboxPatch object.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data”: 3D dataset coordinates
”plot”: 2D coordinates defined by the actual plot limits
”axis”: MPL axis coordinates: (0,0) is lower left; (1,1) is upper right
”figure”: MPL figure coordinates: (0,0) is lower left, (1,1) is upper right
time_offset (float, (value, unit) tuple, or YTQuantity, optional) – Apply an offset to the time shown in the annotation from the value of the current time. If a scalar value with no units is passed in, the value of the time_unit kwarg is used for the units. Default: None, meaning no offset.
text_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib text object. Defaults:
{'color':'white', 'horizontalalignment':'center', 'verticalalignment':'top'}
.inset_box_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib FancyBboxPatch object as the inset box around the text. Defaults:
{'boxstyle':'square', 'pad':0.3, 'facecolor':'black', 'linewidth':3, 'edgecolor':'white', 'alpha':0.5}
Example
>>> import yt >>> ds = yt.load("Enzo_64/DD0020/data0020") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_timestamp()
- annotate_title(title)¶
Accepts a title and adds it to the plot
- annotate_triangle_facets(triangle_vertices, *, plot_args=None, **kwargs)¶
Intended for representing a slice of a triangular faceted geometry in a slice plot.
Uses a set of triangle_vertices to find all triangles the plane of a SlicePlot intersects with. The lines between the intersection points of the triangles are then added to the plot to create an outline of the geometry represented by the triangles.
- annotate_velocity(factor: tuple[int, int] | int = 16, *, scale=None, scale_units=None, normalize=False, plot_args=None, **kwargs)¶
Adds a ‘quiver’ plot of velocity to the plot, skipping all but every factor datapoint. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the velocity fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- property bounds¶
- clear_annotations(index: int | None = None)¶
Clear callbacks from the plot. If index is not set, clear all callbacks. If index is set, clear that index (ie 0 is the first one created, 1 is the 2nd one created, -1 is the last one created, etc.)
- display(name=None, mpl_kwargs=None)¶
Will attempt to show the plot in in an IPython notebook. Failing that, the plot will be saved to disk.
- export_to_mpl_figure(nrows_ncols, axes_pad=1.0, label_mode='L', cbar_location='right', cbar_size='5%', cbar_mode='each', cbar_pad='0%')¶
Creates a matplotlib figure object with the specified axes arrangement, nrows_ncols, and maps the underlying figures to the matplotlib axes. Note that all of these parameters are fed directly to the matplotlib ImageGrid class to create the new figure layout.
- Parameters:
nrows_ncols (tuple) – the number of rows and columns of the axis grid (e.g., nrows_ncols=(2,2,))
axes_pad (float) – padding between axes in inches
label_mode (one of "L", "1", "all") – arrangement of axes that are labeled
cbar_location (one of "left", "right", "bottom", "top") – where to place the colorbar
cbar_size (string (percentage)) – scaling of the colorbar (e.g., “5%”)
cbar_mode (one of "each", "single", "edge", None) – how to represent the colorbar
cbar_pad (string (percentage)) – padding between the axis and colorbar (e.g. “5%”)
- Return type:
The return is a matplotlib figure object.
Examples
>>> import yt >>> ds = yt.load_sample("IsolatedGalaxy") >>> fields = ["density", "velocity_x", "velocity_y", "velocity_magnitude"] >>> p = yt.SlicePlot(ds, "z", fields) >>> p.set_log("velocity_x", False) >>> p.set_log("velocity_y", False) >>> fig = p.export_to_mpl_figure((2, 2)) >>> fig.tight_layout() >>> fig.savefig("test.png")
- flip_horizontal()¶
inverts the horizontal axis (the image’s abscissa)
- flip_vertical()¶
inverts the vertical axis (the image’s ordinate)
- property frb¶
- get_log(field)¶
get the transform type of a field.
- Parameters:
field (string) – the field to get a transform if field == ‘all’, applies to all plots.
- hide_axes(field=None, draw_frame=None)¶
Hides the axes for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object.
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to hide the axes.
draw_frame (boolean) – If True, the axes frame will still be drawn. Defaults to False. See note below for more details.
Examples
This will save an image with no axes.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.save()
This will save an image with no axis or colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.hide_colorbar() >>> s.save()
Note
By default, when removing the axes, the patch on which the axes are drawn is disabled, making it impossible to later change e.g. the background colour. To force the axes patch to be displayed while still hiding the axes, set the
draw_frame
keyword argument toTrue
.
- hide_colorbar(field=None)¶
Hides the colorbar for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object.
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to hide the colorbar. If None or ‘all’ is provided, will default to using all fields available for this object.
Examples
This will save an image with no colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_colorbar() >>> s.save()
This will save an image with no axis or colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.hide_colorbar() >>> s.save()
- list_annotations()¶
List the current callbacks for the plot, along with their index. This index can be used with clear_annotations to remove a callback from the current plot.
- pan(deltas)¶
Pan the image by specifying absolute code unit coordinate deltas.
- Parameters:
deltas (Two-element sequence of floats, quantities, or (float, unit)) –
tuples.
(delta_x, delta_y). If a unit is not supplied the unit is assumed to be code_length.
- pan_rel(deltas)¶
Pan the image by specifying relative deltas, to the FOV.
- Parameters:
deltas (sequence of floats) – (delta_x, delta_y) in relative code unit coordinates
- piter(*args, **kwargs)¶
- refresh()¶
- render() None ¶
Render plots. This operation is expensive and usually doesn’t need to be requested explicitly. In most cases, yt handles rendering automatically and delays it as much as possible to avoid redundant calls on each plot modification (e.g. via annotate_* methods).
However, valid use cases of this method include: - fine control of render (and clear) operations when yt plots are combined with plot
customizations other than plot callbacks (annotate_*)
testing
- run_callbacks()¶
- static sanitize_normal_vector(ds, normal) str | ndarray ¶
Return the name of a cartesian axis whener possible, or a 3-element 1D ndarray of float64 in any other valid case. Fail with a descriptive error message otherwise.
- save(name: str | list[str] | tuple[str, ...] | None = None, suffix: str | None = None, mpl_kwargs: dict[str, Any] | None = None)¶
saves the plot to disk.
- Parameters:
name (string or tuple, optional) – The base of the filename. If name is a directory or if name is not set, the filename of the dataset is used. For a tuple, the resulting path will be given by joining the elements of the tuple
suffix (string, optional) – Specify the image type by its suffix. If not specified, the output type will be inferred from the filename. Defaults to ‘.png’.
mpl_kwargs (dict, optional) – A dict of keyword arguments to be passed to matplotlib.
slc.save(mpl_kwargs={"bbox_inches" (>>>)
- set_antialias(aa)¶
Turn antialiasing on or off.
- Parameters:
aa (boolean)
- set_axes_unit(unit_name)¶
Set the unit for display on the x and y axes of the image.
- Parameters:
unit_name (string or two element tuple of strings) – A unit, available for conversion in the dataset, that the image extents will be displayed in. If set to None, any previous units will be reset. If the unit is None, the default is chosen. If unit_name is ‘1’, ‘u’, or ‘unitary’, it will not display the units, and only show the axes name. If unit_name is a tuple, the first element is assumed to be the unit for the x axis and the second element the unit for the y axis.
- Raises:
YTUnitNotRecognized – If the unit is not known, this will be raised.
Examples
>>> from yt import load >>> ds = load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> p = ProjectionPlot(ds, "y", "Density") >>> p.set_axes_unit("kpc")
- set_background_color(field, color=None)¶
set the background color to match provided color
- Parameters:
field (string) – the field to set the colormap if field == ‘all’, applies to all plots.
color (string or RGBA tuple (optional)) – if set, set the background color to this color if unset, background color is set to the bottom value of the color map
- set_buff_size(size)¶
Sets a new buffer size for the fixed resolution buffer
- Parameters:
size (int or two element sequence of ints) – The number of data elements in the buffer on the x and y axes. If a scalar is provided, then the buffer is assumed to be square.
- set_center(new_center, unit='code_length')¶
Sets a new center for the plot window
- Parameters:
new_center (two element sequence of floats) – The coordinates of the new center of the image in the coordinate system defined by the plot axes. If the unit keyword is not specified, the coordinates are assumed to be in code units.
unit (string) – The name of the unit new_center is given in. If new_center is a YTArray or tuple of YTQuantities, this keyword is ignored.
- set_cmap(field, cmap)¶
set the colormap for one of the fields
- Parameters:
field (string) – the field to set the colormap if field == ‘all’, applies to all plots.
cmap (string or tuple) – If a string, will be interpreted as name of the colormap. If a tuple, it is assumed to be of the form (name, type, number) to be used for palettable functionality. (name, type, number, bool) can be used to specify if a reverse colormap is to be used.
- set_colorbar_label(field, label)¶
Sets the colorbar label.
- set_colorbar_minorticks(field, state)¶
turn colorbar minor ticks on or off in the current plot
Displaying minor ticks reduces performance; turn them off using set_colorbar_minorticks(‘all’, False) if drawing speed is a problem.
- Parameters:
field (string) – the field to remove colorbar minorticks if field == ‘all’, applies to all plots.
state (bool) – the state indicating ‘on’ (True) or ‘off’ (False)
- set_figure_size(size)¶
Sets a new figure size for the plot
- Parameters:
size (float, a sequence of two floats, or None) – The size of the figure (in units of inches), including the margins but not the colorbar. If a single float is passed, it’s interpreted as the size along the long axis. Pass None to reset
- set_font(font_dict=None)¶
Set the font and font properties.
- Parameters:
font_dict (dict) –
A dict of keyword parameters to be passed to
matplotlib.font_manager.FontProperties
.Possible keys include:
family - The font family. Can be serif, sans-serif, cursive, ‘fantasy’ or ‘monospace’.
style - The font style. Either normal, italic or oblique.
color - A valid color string like ‘r’, ‘g’, ‘red’, ‘cobalt’, and ‘orange’.
variant - Either normal or small-caps.
size - Either a relative value of xx-small, x-small, small, medium, large, x-large, xx-large or an absolute font size, e.g. 12
stretch - A numeric value in the range 0-1000 or one of ultra-condensed, extra-condensed, condensed, semi-condensed, normal, semi-expanded, expanded, extra-expanded or ultra-expanded
weight - A numeric value in the range 0-1000 or one of ultralight, light, normal, regular, book, medium, roman, semibold, demibold, demi, bold, heavy, extra bold, or black
See the matplotlib font manager API documentation for more details. https://matplotlib.org/stable/api/font_manager_api.html
Notes
Mathtext axis labels will only obey the size and color keyword.
Examples
This sets the font to be 24-pt, blue, sans-serif, italic, and bold-face.
>>> slc = SlicePlot(ds, "x", "Density") >>> slc.set_font( ... { ... "family": "sans-serif", ... "style": "italic", ... "weight": "bold", ... "size": 24, ... "color": "blue", ... } ... )
- set_font_size(size)¶
Set the size of the font used in the plot
This sets the font size by calling the set_font function. See set_font for more font customization options.
- Parameters:
size (float)
inch). (The absolute size of the font in points (1 pt = 1/72)
- set_log(field, log: bool | None = None, *, linthresh: float | unyt_quantity | tuple[float, Unit | str] | Literal['auto'] | None = None, symlog_auto: bool | None = None)¶
set a field to log, linear, or symlog.
Symlog scaling is a combination of linear and log, where from 0 to a threshold value, it operates as linear, and then beyond that it operates as log. Symlog can also work with negative values in log space as well as negative and positive values simultaneously and symmetrically. If symlog scaling is desired, please set log=True and either set symlog_auto=True or select a value for linthresh.
- Parameters:
field (string) – the field to set a transform if field == ‘all’, applies to all plots.
log (boolean, optional) – set log to True for log scaling, False for linear scaling.
linthresh (float, (float, str), unyt_quantity, or 'auto', optional) – when using symlog scaling, linthresh is the value at which scaling transitions from linear to logarithmic. linthresh must be positive. Note: setting linthresh will automatically enable symlog scale
arguments (Note that log and linthresh are mutually exclusive)
- set_minorticks(field, state)¶
Turn minor ticks on or off in the current plot.
Displaying minor ticks reduces performance; turn them off using set_minorticks(‘all’, False) if drawing speed is a problem.
- Parameters:
field (string) – the field to remove minorticks if field == ‘all’, applies to all plots.
state (bool) – the state indicating ‘on’ (True) or ‘off’ (False)
- set_mpl_projection(mpl_proj)¶
Set the matplotlib projection type with a cartopy transform function
Given a string or a tuple argument, this will project the data onto the plot axes with the chosen transform function.
Assumes that the underlying data has a PlateCarree transform type.
To annotate the plot with coastlines or other annotations, render() will need to be called after this function to make the axes available for annotation.
- Parameters:
mpl_proj (string or tuple) – if passed as a string, mpl_proj is the specified projection type, if passed as a tuple, then tuple will take the form of
("ProjectionType", (args))
or("ProjectionType", (args), {kwargs})
Valid projection type options include: ‘PlateCarree’, ‘LambertConformal’, ‘LabmbertCylindrical’, ‘Mercator’, ‘Miller’, ‘Mollweide’, ‘Orthographic’, ‘Robinson’, ‘Stereographic’, ‘TransverseMercator’, ‘InterruptedGoodeHomolosine’, ‘RotatedPole’, ‘OGSB’, ‘EuroPP’, ‘Geostationary’, ‘Gnomonic’, ‘NorthPolarStereo’, ‘OSNI’, ‘SouthPolarStereo’, ‘AlbersEqualArea’, ‘AzimuthalEquidistant’, ‘Sinusoidal’, ‘UTM’, ‘NearsidePerspective’, ‘LambertAzimuthalEqualArea’
Examples
This will create a Mollweide projection using Mollweide default values and annotate it with coastlines
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection("AIRDENS", "Mollweide") >>> p.render() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will move the PlateCarree central longitude to 90 degrees and annotate with coastlines.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection( ... "AIRDENS", ("PlateCarree", (), {"central_longitude": 90, "globe": None}) ... ) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will create a RoatatedPole projection with the unrotated pole position at 37.5 degrees latitude and 177.5 degrees longitude by passing them in as args.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection("RotatedPole", (177.5, 37.5)) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will create a RoatatedPole projection with the unrotated pole position at 37.5 degrees latitude and 177.5 degrees longitude by passing them in as kwargs.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection( ... ("RotatedPole", (), {"pole_latitude": 37.5, "pole_longitude": 177.5}) ... ) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
- set_norm(field, norm: Normalize)¶
Set a custom
matplotlib.colors.Normalize
to plot field.Any constraints previously set with set_log, set_zlim will be dropped.
Note that any float value attached to norm (e.g. vmin, vmax, vcenter …) will be read in the current displayed units, which can be controlled with the set_unit method.
- Parameters:
field (str or tuple[str, str]) – if field == ‘all’, applies to all plots.
norm (matplotlib.colors.Normalize) – see https://matplotlib.org/stable/tutorials/colors/colormapnorms.html
- set_origin(origin)¶
Set the plot origin.
- Parameters:
origin (string or length 1, 2, or 3 sequence.) – The location of the origin of the plot coordinate system. This is typically represented by a ‘-’ separated string or a tuple of strings. In the first index the y-location is given by ‘lower’, ‘upper’, or ‘center’. The second index is the x-location, given as ‘left’, ‘right’, or ‘center’. Finally, whether the origin is applied in ‘domain’ space, plot ‘window’ space or ‘native’ simulation coordinate system is given. For example, both ‘upper-right-domain’ and [‘upper’, ‘right’, ‘domain’] place the origin in the upper right hand corner of domain space. If x or y are not given, a value is inferred. For instance, ‘left-domain’ corresponds to the lower-left hand corner of the simulation domain, ‘center-domain’ corresponds to the center of the simulation domain, or ‘center-window’ for the center of the plot window. In the event that none of these options place the origin in a desired location, a sequence of tuples and a string specifying the coordinate space can be given. If plain numeric types are input, units of code_length are assumed. Further examples:
=============================== (===============================================)
example (format)
===============================
'domain' ('{space}')
'left-window' ('{xloc}-{space}')
'upper-domain' ('{yloc}-{space}')
'lower-right-window' ('{yloc}-{xloc}-{space}')
('{space}'
('window' ())
)
('{xloc}'
('right' ('{space}'))
'domain')
('{yloc}'
('lower' ('{space}'))
'window')
('{yloc}'
'{xloc}'
('lower'
'right'
'window')
((yloc
'{unit}')
(xloc
'{unit}')
((0 ('{space}'))
'm')
(.4
'm')
'window')
(xloc
yloc
(0.23 ('{space}'))
0.5
'domain')
===============================
- set_unit(field, new_unit, equivalency=None, equivalency_kwargs=None)¶
Sets a new unit for the requested field
- Parameters:
field (string or field tuple) – The name of the field that is to be changed.
new_unit (string or Unit object)
equivalency (string, optional) – If set, the equivalency to use to convert the current units to the new requested unit. If None, the unit conversion will be done without an equivalency
equivalency_kwargs (string, optional) – Keyword arguments to be passed to the equivalency. Only used if
equivalency
is set.
- set_width(width, unit=None)¶
set the width of the plot window
- Parameters:
width (float, array of floats, (float, unit) tuple, or tuple of) –
(float, unit) tuples.
Width can have four different formats to support windows with variable x and y widths. They are:
format
example
(float, string)
(10,’kpc’)
((float, string), (float, string))
((10,’kpc’),(15,’kpc’))
float
0.2
(float, float)
(0.2, 0.3)
For example, (10, ‘kpc’) requests a plot window that is 10 kiloparsecs wide in the x and y directions, ((10,’kpc’),(15,’kpc’)) requests a window that is 10 kiloparsecs wide along the x axis and 15 kiloparsecs wide along the y axis. In the other two examples, code units are assumed, for example (0.2, 0.3) requests a plot that has an x width of 0.2 and a y width of 0.3 in code units. If units are provided the resulting plot axis labels will use the supplied units.
unit (str) – the unit the width has been specified in. If width is a tuple, this argument is ignored. Defaults to code units.
- set_xlabel(label)¶
Allow the user to modify the X-axis title Defaults to the global value. Fontsize defaults to 18.
- Parameters:
label (str) – The new string for the x-axis.
(cm$^{-3}$)") (>>> plot.set_xlabel("H2I Number Density)
- set_ylabel(label)¶
Allow the user to modify the Y-axis title Defaults to the global value.
- Parameters:
label (str) – The new string for the y-axis.
(K)") (>>> plot.set_ylabel("Temperature)
- set_zlim(field, zmin: ~unyt.array.unyt_quantity | tuple[float, ~unyt.unit_object.Unit | str] | float | ~typing.Literal['min'] | ~yt.visualization.plot_container.Unset = <yt.visualization.plot_container.Unset object>, zmax: ~unyt.array.unyt_quantity | tuple[float, ~unyt.unit_object.Unit | str] | float | ~typing.Literal['max'] | ~yt.visualization.plot_container.Unset = <yt.visualization.plot_container.Unset object>, dynamic_range: float | None = None)¶
set the scale of the colormap
- Parameters:
field (string) – the field to set a colormap scale if field == ‘all’, applies to all plots.
zmin (float, Quantity, or 'min') – the new minimum of the colormap scale. If ‘min’, will set to the minimum value in the current view.
zmax (float, Quantity, or 'max') – the new maximum of the colormap scale. If ‘max’, will set to the maximum value in the current view.
dynamic_range (float (default: None)) – The dynamic range of the image. If zmin == None, will set zmin = zmax / dynamic_range If zmax == None, will set zmax = zmin * dynamic_range
- setup_callbacks()¶
- show()¶
This will send any existing plots to the IPython notebook.
If yt is being run from within an IPython session, and it is able to determine this, this function will send any existing plots to the notebook for display.
If yt can’t determine if it’s inside an IPython session, it will raise YTNotInsideNotebook.
Examples
>>> from yt import SlicePlot >>> slc = SlicePlot( ... ds, "x", [("gas", "density"), ("gas", "velocity_magnitude")] ... ) >>> slc.show()
- show_axes(field=None)¶
Shows the axes for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object. See hide_axes().
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to show the axes.
- show_colorbar(field=None)¶
Shows the colorbar for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object. See hide_colorbar().
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional))
colorbar. (The name of the field(s) that we want to show the)
- swap_axes()¶
- to_fits_data(fields=None, other_keys=None, length_unit=None, **kwargs)¶
Export the fields in this PlotWindow instance to a FITSImageData instance.
This will export a set of FITS images of either the fields specified or all the fields already in the object.
- Parameters:
fields (list of strings) – These fields will be pixelized and output. If “None”, the keys of the FRB will be used.
other_keys (dictionary, optional) – A set of header keys and values to write into the FITS header.
length_unit (string, optional) – the length units that the coordinates are written in. The default is to use the default length unit of the dataset.
- property width¶
- class yt.visualization.plot_window.NormalPlot[source]¶
Bases:
object
This is the abstraction for SlicePlot and ProjectionPlot, where we define the common sanitizing mechanism for user input (normal direction). It is implemented as a mixin class.
- class yt.visualization.plot_window.OffAxisProjectionDummyDataSource(center, ds, normal_vector, width, fields, interpolated, weight=None, volume=None, no_ghost=False, le=None, re=None, north_vector=None, depth=None, method='integrate', data_source=None, *, moment=1)[source]¶
Bases:
object
- class yt.visualization.plot_window.OffAxisProjectionPlot(ds, normal, fields, *args, **kwargs)[source]¶
Bases:
ProjectionPlot
,PWViewerMPL
Creates an off axis projection plot from a dataset
Given a ds object, a normal vector to project along, and a field name string, this will return a PWViewerMPL object containing the plot.
The plot can be updated using one of the many helper functions defined in PlotWindow.
- Parameters:
ds (
yt.data_objects.static_output.Dataset
) – This is the dataset object corresponding to the simulation output to be plotted.normal (a sequence of floats) – The vector normal to the slicing plane.
fields (string) – The name of the field(s) to be plotted.
center ('center', 'c', id of a global extremum, or array-like) –
The coordinate of the selection’s center. Defaults to the ‘center’, i.e. center of the domain.
Centering on the min or max of a field is supported by passing a tuple such as (‘min’, (‘gas’, ‘density’)) or (‘max’, (‘gas’, ‘temperature’). A single string may also be used (e.g. “min_density” or “max_temperature”), though it’s not as flexible and does not allow to select an exact field/particle type. With this syntax, the first field matching the provided name is selected. ‘max’ or ‘m’ can be used as a shortcut for (‘max’, (‘gas’, ‘density’)) ‘min’ can be used as a shortcut for (‘min’, (‘gas’, ‘density’))
One can also select an exact point as a 3 element coordinate sequence, e.g. [0.5, 0.5, 0] Units can be specified by passing in center as a tuple containing a 3-element coordinate sequence and string unit name, e.g. ([0, 0.5, 0.5], “cm”), or by passing in a YTArray. Code units are assumed if unspecified.
width (tuple or a float.) –
Width can have four different formats to support windows with variable x and y widths. They are:
format
example
(float, string)
(10,’kpc’)
((float, string), (float, string))
((10,’kpc’),(15,’kpc’))
float
0.2
(float, float)
(0.2, 0.3)
For example, (10, ‘kpc’) requests a plot window that is 10 kiloparsecs wide in the x and y directions, ((10,’kpc’),(15,’kpc’)) requests a window that is 10 kiloparsecs wide along the x axis and 15 kiloparsecs wide along the y axis. In the other two examples, code units are assumed, for example (0.2, 0.3) requests a plot that has an x width of 0.2 and a y width of 0.3 in code units. If units are provided the resulting plot axis labels will use the supplied units.
depth (A tuple or a float) – A tuple containing the depth to project through and the string key of the unit: (width, ‘unit’). If set to a float, code units are assumed
weight_field (string) – The name of the weighting field. Set to None for no weight.
max_level (int) – The maximum level to project to.
axes_unit (string) – The name of the unit for the tick labels on the x and y axes. Defaults to None, which automatically picks an appropriate unit. If axes_unit is ‘1’, ‘u’, or ‘unitary’, it will not display the units, and only show the axes name.
north_vector (a sequence of floats) – A vector defining the ‘up’ direction in the plot. This option sets the orientation of the slicing plane. If not set, an arbitrary grid-aligned north-vector is chosen.
fontsize (integer) – The size of the fonts for the axis, colorbar, and tick labels.
method (string) –
The method of projection. Valid methods are:
”integrate” with no weight_field specified : integrate the requested field along the line of sight.
”integrate” with a weight_field specified : weight the requested field by the weighting field and integrate along the line of sight.
”sum” : This method is the same as integrate, except that it does not multiply by a path length when performing the integration, and is just a straight summation of the field along the given axis. WARNING: This should only be used for uniform resolution grid datasets, as other datasets may result in unphysical images.
moment (integer, optional) – for a weighted projection, moment = 1 (the default) corresponds to a weighted average. moment = 2 corresponds to a weighted standard deviation.
data_source (YTSelectionContainer object) – Object to be used for data selection. Defaults to ds.all_data(), a region covering the full domain
buff_size (length 2 sequence) – Size of the buffer to use for the image, i.e. the number of resolution elements used. Effectively sets a resolution limit to the image if buff_size is smaller than the finest gridding.
- annotate_arrow(pos, *, length=0.03, width=0.0001, head_width=0.01, head_length=0.01, starting_pos=None, coord_system='data', plot_args: dict[str, Any] | None = None, **kwargs)¶
Overplot arrow(s) pointing at position(s) for highlighting specific features. By default, arrow points from lower left to the designated position “pos” with arrow length “length”. Alternatively, if “starting_pos” is set, arrow will stretch from “starting_pos” to “pos” and “length” will be disregarded.
“coord_system” keyword refers to positions set in “pos” arg and “starting_pos” keyword, which by default are in data coordinates.
“length”, “width”, “head_length”, and “head_width” keywords for the arrow are all in axis units, ie relative to the size of the plot axes as 1, even if the position of the arrow is set relative to another coordinate system.
- Parameters:
pos (array-like) – These are the coordinates where the marker(s) will be overplotted Either as [x,y,z] or as [[x1,x2,…],[y1,y2,…],[z1,z2,…]]
length (float, optional) – The length, in axis units, of the arrow. Default: 0.03
width (float, optional) – The width, in axis units, of the tail line of the arrow. Default: 0.003
head_length (float, optional) – The length, in axis units, of the head of the arrow. If set to None, use 1.5*head_width Default: None
head_width (float, optional) – The width, in axis units, of the head of the arrow. Default: 0.02
starting_pos (2- or 3-element tuple, list, or array, optional) – These are the coordinates from which the arrow starts towards its point. Not compatible with ‘length’ kwarg.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
plot_args (dictionary, optional) – This dictionary is passed to the MPL arrow function for generating the arrow. By default, it is: {‘color’:’white’}
Examples
>>> # Overplot an arrow pointing to feature at data coord: (0.2, 0.3, 0.4) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_arrow([0.2, 0.3, 0.4]) >>> s.save()
>>> # Overplot a red arrow with longer length pointing to plot coordinate >>> # (0.1, -0.1) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_arrow( ... [0.1, -0.1], length=0.06, coord_system="plot", color="red" ... ) >>> s.save()
- annotate_cell_edges(line_width=0.002, alpha=1.0, color='black')¶
Annotate cell edges. This is done through a second call to pixelize, where the distance from a pixel to a cell boundary in pixels is compared against the line_width argument. The secondary image is colored as color and overlaid with the alpha value.
- Parameters:
line_width (float) – The width of the cell edge lines in normalized units relative to the size of the longest axis. Default is 1% of the size of the smallest axis.
alpha (float) – When the second image is overlaid, it will have this level of alpha transparency. Default is 1.0 (fully-opaque).
color (tuple of three floats or matplotlib color name) – This is the color of the cell edge values. It defaults to black.
Examples
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_cell_edges() >>> s.save()
- annotate_clumps(clumps, *, plot_args=None, **kwargs)¶
Take a list of clumps and plot them as a set of contours.
- annotate_contour(field: tuple[str, str] | str, levels: int = 5, *, factor: tuple[int, int] | int = 4, clim: tuple[float, float] | None = None, label: bool = False, take_log: bool | None = None, data_source: YTDataContainer | None = None, plot_args: dict[str, Any] | None = None, text_args: dict[str, Any] | None = None, ncont: int | None = None) None ¶
Add contours in field to the plot. levels governs the number of contours generated, factor governs the number of points used in the interpolation, take_log governs how it is contoured and clim gives the (lower, upper) limits for contouring. An alternate data source can be specified with data_source, but by default the plot’s data source will be queried.
- annotate_cquiver(field_x, field_y, field_c=None, *, factor: tuple[int, int] | int = 16, scale=None, scale_units=None, normalize=False, plot_args=None, **kwargs)¶
Get a quiver plot on top of a cutting plane, using field_x and field_y, skipping every factor datapoint in the discretization. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- annotate_grids(alpha=0.7, min_pix=1, min_pix_ids=20, draw_ids=False, id_loc=None, periodic=True, min_level=None, max_level=None, cmap='B-W LINEAR_r', edgecolors=None, linewidth=1.0)¶
Draws grids on an existing PlotWindow object. Adds grid boundaries to a plot, optionally with alpha-blending. By default, colors different levels of grids with different colors going from white to black, but you can change to any arbitrary colormap with cmap keyword, to all black grid edges for all levels with cmap=None and edgecolors=None, or to an arbitrary single color for grid edges with edgecolors=’YourChosenColor’ defined in any of the standard ways (e.g., edgecolors=’white’, edgecolors=’r’, edgecolors=’#00FFFF’, or edgecolor=’0.3’, where the last is a float in 0-1 scale indicating gray). Note that setting edgecolors overrides cmap if you have both set to non-None values. Cutoff for display is at min_pix wide. draw_ids puts the grid id a the corner of the grid (but its not so great in projections…). id_loc determines which corner holds the grid id. One can set min and maximum level of grids to display, and can change the linewidth of the displayed grids.
- annotate_line(p1, p2, *, coord_system='data', plot_args: dict[str, Any] | None = None, **kwargs)¶
Overplot a line with endpoints at p1 and p2. p1 and p2 should be 2D or 3D coordinates consistent with the coordinate system denoted in the “coord_system” keyword.
- Parameters:
p1 (2- or 3-element tuples, lists, or arrays) – These are the coordinates of the endpoints of the line.
p2 (2- or 3-element tuples, lists, or arrays) – These are the coordinates of the endpoints of the line.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates p1 and p2. Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
plot_args (dictionary, optional) – This dictionary is passed to the MPL plot function for generating the line. By default, it is: {‘color’:’white’, ‘linewidth’:2}
Examples
>>> # Overplot a diagonal white line from the lower left corner to upper >>> # right corner >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_line([0, 0], [1, 1], coord_system="axis") >>> s.save()
>>> # Overplot a red dashed line from data coordinate (0.1, 0.2, 0.3) to >>> # (0.5, 0.6, 0.7) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_line( ... [0.1, 0.2, 0.3], ... [0.5, 0.6, 0.7], ... coord_system="data", ... color="red", ... linestyles="--", ... ) >>> s.save()
- annotate_line_integral_convolution(field_x, field_y, texture=None, kernellen=50.0, lim=(0.5, 0.6), cmap='binary', alpha=0.8, const_alpha=False)¶
Add the line integral convolution to the plot for vector fields visualization. Two component of vector fields needed to be provided (i.e., velocity_x and velocity_y, magnetic_field_x and magnetic_field_y).
- Parameters:
field_x (string) – The names of two components of vector field which will be visualized
field_y (string) – The names of two components of vector field which will be visualized
texture (2-d array with the same shape of image, optional) – Texture will be convolved when computing line integral convolution. A white noise background will be used as default.
kernellen (float, optional) – The lens of kernel for convolution, which is the length over which the convolution will be performed. For longer kernellen, longer streamline structure will appear.
lim (2-element tuple, list, or array, optional) – The value of line integral convolution will be clipped to the range of lim, which applies upper and lower bounds to the values of line integral convolution and enhance the visibility of plots. Each element should be in the range of [0,1].
cmap (string, optional) – The name of colormap for line integral convolution plot.
alpha (float, optional) – The alpha value for line integral convolution plot.
const_alpha (boolean, optional) – If set to False (by default), alpha will be weighted spatially by the values of line integral convolution; otherwise a constant value of the given alpha is used.
Example
>>> import yt >>> ds = yt.load("Enzo_64/DD0020/data0020") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_line_integral_convolution( ... "velocity_x", "velocity_y", lim=(0.5, 0.65) ... )
- annotate_magnetic_field(factor: tuple[int, int] | int = 16, *, scale=None, scale_units=None, normalize=False, plot_args=None, **kwargs)¶
Adds a ‘quiver’ plot of magnetic field to the plot, skipping all but every factor datapoint. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the magnetic fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- annotate_marker(pos, marker='x', *, coord_system='data', plot_args=None, **kwargs)¶
Overplot marker(s) at a position(s) for highlighting specific features.
- Parameters:
pos (array-like) – These are the coordinates where the marker(s) will be overplotted Either as [x,y,z] or as [[x1,x2,…],[y1,y2,…],[z1,z2,…]]
marker (string, optional) – The shape of the marker to be passed to the MPL scatter function. By default, it is ‘x’, but other acceptable values are: ‘.’, ‘o’, ‘v’, ‘^’, ‘s’, ‘p’ ‘*’, etc. See matplotlib.markers for more information.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
plot_args (dictionary, optional) – This dictionary is passed to the MPL scatter function for generating the marker. By default, it is: {‘color’:’white’, ‘s’:50}
Examples
>>> # Overplot a white X on a feature at data location (0.5, 0.5, 0.5) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_marker([0.4, 0.5, 0.6]) >>> s.save()
>>> # Overplot a big yellow circle at axis location (0.1, 0.2) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_marker( ... [0.1, 0.2], ... marker="o", ... coord_system="axis", ... color="yellow", ... s=200, ... ) >>> s.save()
- annotate_mesh_lines(*, plot_args=None, **kwargs)¶
Adds mesh lines to the plot. Only works for unstructured or semi-structured mesh data. For structured grid data, see GridBoundaryCallback or CellEdgesCallback.
- Parameters:
plot_args (dict, optional) – A dictionary of arguments that will be passed to matplotlib.
Example
>>> import yt >>> ds = yt.load("MOOSE_sample_data/out.e-s010") >>> sl = yt.SlicePlot(ds, "z", ("connect2", "convected")) >>> sl.annotate_mesh_lines(color="black")
- annotate_particles(width, p_size=1.0, col='k', marker='o', stride=1, ptype='all', alpha=1.0, data_source=None)¶
Adds particle positions, based on a thick slab along axis with a width along the line of sight. p_size controls the number of pixels per particle, and col governs the color. ptype will restrict plotted particles to only those that are of a given type. alpha determines the opacity of the marker symbol used in the scatter. An alternate data source can be specified with data_source, but by default the plot’s data source will be queried.
- annotate_quiver(field_x, field_y, field_c=None, *, factor: tuple[int, int] | int = 16, scale=None, scale_units=None, normalize=False, bv_x=0, bv_y=0, plot_args=None, **kwargs)¶
Adds a ‘quiver’ plot to any plot, using the field_x and field_y from the associated data, skipping every factor pixels. field_c is an optional field name used for color. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- annotate_ray(ray, *, arrow=False, plot_args=None, **kwargs)¶
Adds a line representing the projected path of a ray across the plot. The ray can be either a YTOrthoRay, YTRay, or a LightRay object. annotate_ray() will properly account for periodic rays across the volume. If arrow is set to True, uses the MPL.pyplot.arrow function, otherwise uses the MPL.pyplot.plot function to plot a normal line. Adjust plot_args accordingly.
- Parameters:
ray (YTOrthoRay, YTRay, or LightRay) – Ray is the object that we want to include. We overplot the projected trajectory of the ray. If the object is a trident.LightRay object, it will only plot the segment of the LightRay that intersects the dataset currently displayed.
arrow (boolean, optional) – Whether or not to place an arrowhead on the front of the ray to denote direction Default: False
plot_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib line object. Defaults: {‘color’:’white’, ‘linewidth’:2}.
Examples
>>> # Overplot a ray and an ortho_ray object on a projection >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> oray = ds.ortho_ray(1, (0.3, 0.4)) # orthoray down the y axis >>> ray = ds.ray((0.1, 0.2, 0.3), (0.6, 0.7, 0.8)) # arbitrary ray >>> p = yt.ProjectionPlot(ds, "z", "density") >>> p.annotate_ray(oray) >>> p.annotate_ray(ray) >>> p.save()
>>> # Overplot a LightRay object on a projection >>> import yt >>> from trident import LightRay >>> ds = yt.load("enzo_cosmology_plus/RD0004/RD0004") >>> lr = LightRay( ... "enzo_cosmology_plus/AMRCosmology.enzo", "Enzo", 0.0, 0.1, time_data=False ... ) >>> lray = lr.make_light_ray(seed=1) >>> p = yt.ProjectionPlot(ds, "z", "density") >>> p.annotate_ray(lr) >>> p.save()
- annotate_scale(*, corner='lower_right', coeff=None, unit=None, pos=None, max_frac=0.16, min_frac=0.015, coord_system='axis', text_args=None, size_bar_args=None, draw_inset_box=False, inset_box_args=None, scale_text_format='{scale} {units}')¶
Annotates the scale of the plot at a specified location in the image (either in a preset corner, or by specifying (x,y) image coordinates with the pos argument. Coeff and units (e.g. 1 Mpc or 100 kpc) refer to the distance scale you desire to show on the plot. If no coeff and units are specified, an appropriate pair will be determined such that your scale bar is never smaller than min_frac or greater than max_frac of your plottable axis length. Additional customization of the scale bar is possible by adjusting the text_args and size_bar_args dictionaries. The text_args dictionary accepts matplotlib’s font_properties arguments to override the default font_properties for the current plot. The size_bar_args dictionary accepts keyword arguments for the AnchoredSizeBar class in matplotlib’s axes_grid toolkit.
- Parameters:
corner (string, optional) – Corner sets up one of 4 predeterimined locations for the scale bar to be displayed in the image: ‘upper_left’, ‘upper_right’, ‘lower_left’, ‘lower_right’ (also allows None). This value will be overridden by the optional ‘pos’ keyword.
coeff (float, optional) – The coefficient of the unit defining the distance scale (e.g. 10 kpc or 100 Mpc) for overplotting. If set to None along with unit keyword, coeff will be automatically determined to be a power of 10 relative to the best-fit unit.
unit (string, optional) – unit must be a valid yt distance unit (e.g. ‘m’, ‘km’, ‘AU’, ‘pc’, ‘kpc’, etc.) or set to None. If set to None, will be automatically determined to be the best-fit to the data.
pos (2- or 3-element tuples, lists, or arrays, optional) – The image location of the scale bar in the plot coordinate system. Setting pos overrides the corner parameter.
min_frac (float, optional) – The minimum/maximum fraction of the axis width for the scale bar to extend. A value of 1 would allow the scale bar to extend across the entire axis width. Only used for automatically calculating best-fit coeff and unit when neither is specified, otherwise disregarded.
max_frac (float, optional) – The minimum/maximum fraction of the axis width for the scale bar to extend. A value of 1 would allow the scale bar to extend across the entire axis width. Only used for automatically calculating best-fit coeff and unit when neither is specified, otherwise disregarded.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data”: 3D dataset coordinates
”plot”: 2D coordinates defined by the actual plot limits
”axis”: MPL axis coordinates: (0,0) is lower left; (1,1) is upper right
”figure”: MPL figure coordinates: (0,0) is lower left, (1,1) is upper right
text_args (dictionary, optional) – A dictionary of parameters to used to update the font_properties for the text in this callback. For any property not set, it will use the defaults of the plot. Thus one can modify the text size with
text_args={'size':24}
size_bar_args (dictionary, optional) – A dictionary of parameters to be passed to the Matplotlib AnchoredSizeBar initializer. Defaults:
{'pad': 0.25, 'sep': 5, 'borderpad': 1, 'color': 'w'}
draw_inset_box (boolean, optional) – Whether or not an inset box should be included around the scale bar.
inset_box_args (dictionary, optional) – A dictionary of keyword arguments to be passed to the matplotlib Patch object that represents the inset box. Defaults:
{'facecolor': 'black', 'linewidth': 3, 'edgecolor': 'white', 'alpha': 0.5, 'boxstyle': 'square'}
scale_text_format (string, optional) – This specifies the format of the scalebar value assuming “scale” is the numerical value and “unit” is units of the scale (e.g. ‘cm’, ‘kpc’, etc.) The scale can be specified to arbitrary precision according to printf formatting codes. The format string must only specify “scale” and “units”. Example: “Length = {scale:.2f} {units}”. Default: “{scale} {units}”
Example
>>> import yt >>> ds = yt.load("Enzo_64/DD0020/data0020") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_scale()
- annotate_sphere(center, radius, *, coord_system='data', text=None, circle_args=None, text_args=None)¶
Overplot a circle with designated center and radius with optional text.
- Parameters:
center (2- or 3-element tuple, list, or array) – These are the coordinates where the circle will be overplotted
radius (YTArray, float, or (1, ('kpc')) style tuple) – The radius of the circle in code coordinates
circle_args (dict, optional) – This dictionary is passed to the MPL circle object. By default, {‘color’:’white’}
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
text (string, optional) – Optional text to include next to the circle.
text_args (dictionary, optional) – This dictionary is passed to the MPL text function. By default, it is: {‘color’:’white’}
Examples
>>> # Overplot a white circle of radius 100 kpc over the central galaxy >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_sphere([0.5, 0.5, 0.5], radius=(100, "kpc")) >>> s.save()
- annotate_streamlines(field_x: tuple[str, str] | str, field_y: tuple[str, str] | str, *, linewidth: float | tuple[str, str] | str = 1.0, linewidth_upscaling: float = 1.0, color: Any | tuple[str, str] | None = None, color_threshold: float | unyt_quantity = -inf, factor: tuple[int, int] | int = 16, field_color=None, display_threshold=None, plot_args=None, **kwargs)¶
Plot streamlines using matplotlib.axes.Axes.streamplot
- Parameters:
field_x (field key) – The “velocity” analoguous field along the horizontal direction.
field_y (field key) – The “velocity” analoguous field along the vertical direction.
linewidth (float, or field key (default: 1.0)) – A constant scalar will be passed directly to matplotlib.axes.Axes.streamplot A field key will be first interpreted by yt and produce the adequate 2D array. Data fields are normalized by their maximum value, so the maximal linewidth is 1 by default. See linewidth_upscaling for fine tuning. Note that the absolute value is taken in all cases.
linewidth_upscaling (float (default: 1.0)) – A constant multiplicative factor applied to linewidth. Final linewidth is obtained as: linewidth_upscaling * abs(linewidth) / max(abs(linewidth))
color (a color identifier, or a field key (default: matplotlib.rcParams['line.color'])) – A constant color identifier will be passed directly to matplotlib.axes.Axes.streamplot A field key will be first interpreted by yt and produce the adequate 2D array. See https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.streamplot.html for how to customize color mapping using cmap and norm arguments.
color_threshold (float or unyt_quantity (default: -inf)) – Regions where the field used for color is lower than this threshold will be masked. Only used if color is a field key.
factor (int, or tuple[int, int] (default: 16)) – Fields are downed-sampled by this factor with respect to the background image buffer size. A single integer factor will be used for both direction, but a tuple of 2 integers can be passed to set x and y downsampling independently.
**kwargs (any additional keyword arguments will be passed) – directly to matplotlib.axes.Axes.streamplot
- annotate_text(pos, text, *, coord_system='data', text_args=None, inset_box_args=None)¶
Overplot text on the plot at a specified position. If you desire an inset box around your text, set one with the inset_box_args dictionary keyword.
- Parameters:
pos (2- or 3-element tuple, list, or array) – These are the coordinates where the text will be overplotted
text (string) – The text you wish to include
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
text_args (dictionary, optional) – This dictionary is passed to the MPL text function for generating the text. By default, it is: {‘color’:’white’} and uses the defaults for the other fonts in the image.
inset_box_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib FancyBboxPatch object as the inset box around the text. Default: {}
Examples
>>> # Overplot white text at data location [0.55, 0.7, 0.4] >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_text([0.55, 0.7, 0.4], "Here is a galaxy") >>> s.save()
>>> # Overplot yellow text at axis location [0.2, 0.8] with >>> # a shaded inset box >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_text( ... [0.2, 0.8], ... "Here is a galaxy", ... coord_system="axis", ... text_args={"color": "yellow"}, ... inset_box_args={ ... "boxstyle": "square,pad=0.3", ... "facecolor": "black", ... "linewidth": 3, ... "edgecolor": "white", ... "alpha": 0.5, ... }, ... ) >>> s.save()
- annotate_timestamp(x_pos=None, y_pos=None, corner='lower_left', *, time=True, redshift=False, time_format='t = {time:.1f} {units}', time_unit=None, redshift_format='z = {redshift:.2f}', draw_inset_box=False, coord_system='axis', time_offset=None, text_args=None, inset_box_args=None)¶
Annotates the timestamp and/or redshift of the data output at a specified location in the image (either in a present corner, or by specifying (x,y) image coordinates with the x_pos, y_pos arguments. If no time_units are specified, it will automatically choose appropriate units. It allows for custom formatting of the time and redshift information, as well as the specification of an inset box around the text.
- Parameters:
x_pos (floats, optional) – The image location of the timestamp in the coord system defined by the coord_system kwarg. Setting x_pos and y_pos overrides the corner parameter.
y_pos (floats, optional) – The image location of the timestamp in the coord system defined by the coord_system kwarg. Setting x_pos and y_pos overrides the corner parameter.
corner (string, optional) – Corner sets up one of 4 predeterimined locations for the timestamp to be displayed in the image: ‘upper_left’, ‘upper_right’, ‘lower_left’, ‘lower_right’ (also allows None). This value will be overridden by the optional x_pos and y_pos keywords.
time (boolean, optional) – Whether or not to show the ds.current_time of the data output. Can be used solo or in conjunction with redshift parameter.
redshift (boolean, optional) – Whether or not to show the ds.current_time of the data output. Can be used solo or in conjunction with the time parameter.
time_format (string, optional) – This specifies the format of the time output assuming “time” is the number of time and “unit” is units of the time (e.g. ‘s’, ‘Myr’, etc.) The time can be specified to arbitrary precision according to printf formatting codes (defaults to .1f – a float with 1 digits after decimal). Example: “Age = {time:.2f} {units}”.
time_unit (string, optional) – time_unit must be a valid yt time unit (e.g. ‘s’, ‘min’, ‘hr’, ‘yr’, ‘Myr’, etc.)
redshift_format (string, optional) – This specifies the format of the redshift output. The redshift can be specified to arbitrary precision according to printf formatting codes (defaults to 0.2f – a float with 2 digits after decimal). Example: “REDSHIFT = {redshift:03.3g}”,
draw_inset_box (boolean, optional) – Whether or not an inset box should be included around the text If so, it uses the inset_box_args to set the matplotlib FancyBboxPatch object.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data”: 3D dataset coordinates
”plot”: 2D coordinates defined by the actual plot limits
”axis”: MPL axis coordinates: (0,0) is lower left; (1,1) is upper right
”figure”: MPL figure coordinates: (0,0) is lower left, (1,1) is upper right
time_offset (float, (value, unit) tuple, or YTQuantity, optional) – Apply an offset to the time shown in the annotation from the value of the current time. If a scalar value with no units is passed in, the value of the time_unit kwarg is used for the units. Default: None, meaning no offset.
text_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib text object. Defaults:
{'color':'white', 'horizontalalignment':'center', 'verticalalignment':'top'}
.inset_box_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib FancyBboxPatch object as the inset box around the text. Defaults:
{'boxstyle':'square', 'pad':0.3, 'facecolor':'black', 'linewidth':3, 'edgecolor':'white', 'alpha':0.5}
Example
>>> import yt >>> ds = yt.load("Enzo_64/DD0020/data0020") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_timestamp()
- annotate_title(title)¶
Accepts a title and adds it to the plot
- annotate_triangle_facets(triangle_vertices, *, plot_args=None, **kwargs)¶
Intended for representing a slice of a triangular faceted geometry in a slice plot.
Uses a set of triangle_vertices to find all triangles the plane of a SlicePlot intersects with. The lines between the intersection points of the triangles are then added to the plot to create an outline of the geometry represented by the triangles.
- annotate_velocity(factor: tuple[int, int] | int = 16, *, scale=None, scale_units=None, normalize=False, plot_args=None, **kwargs)¶
Adds a ‘quiver’ plot of velocity to the plot, skipping all but every factor datapoint. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the velocity fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- property bounds¶
- clear_annotations(index: int | None = None)¶
Clear callbacks from the plot. If index is not set, clear all callbacks. If index is set, clear that index (ie 0 is the first one created, 1 is the 2nd one created, -1 is the last one created, etc.)
- display(name=None, mpl_kwargs=None)¶
Will attempt to show the plot in in an IPython notebook. Failing that, the plot will be saved to disk.
- export_to_mpl_figure(nrows_ncols, axes_pad=1.0, label_mode='L', cbar_location='right', cbar_size='5%', cbar_mode='each', cbar_pad='0%')¶
Creates a matplotlib figure object with the specified axes arrangement, nrows_ncols, and maps the underlying figures to the matplotlib axes. Note that all of these parameters are fed directly to the matplotlib ImageGrid class to create the new figure layout.
- Parameters:
nrows_ncols (tuple) – the number of rows and columns of the axis grid (e.g., nrows_ncols=(2,2,))
axes_pad (float) – padding between axes in inches
label_mode (one of "L", "1", "all") – arrangement of axes that are labeled
cbar_location (one of "left", "right", "bottom", "top") – where to place the colorbar
cbar_size (string (percentage)) – scaling of the colorbar (e.g., “5%”)
cbar_mode (one of "each", "single", "edge", None) – how to represent the colorbar
cbar_pad (string (percentage)) – padding between the axis and colorbar (e.g. “5%”)
- Return type:
The return is a matplotlib figure object.
Examples
>>> import yt >>> ds = yt.load_sample("IsolatedGalaxy") >>> fields = ["density", "velocity_x", "velocity_y", "velocity_magnitude"] >>> p = yt.SlicePlot(ds, "z", fields) >>> p.set_log("velocity_x", False) >>> p.set_log("velocity_y", False) >>> fig = p.export_to_mpl_figure((2, 2)) >>> fig.tight_layout() >>> fig.savefig("test.png")
- flip_horizontal()¶
inverts the horizontal axis (the image’s abscissa)
- flip_vertical()¶
inverts the vertical axis (the image’s ordinate)
- property frb¶
- get_log(field)¶
get the transform type of a field.
- Parameters:
field (string) – the field to get a transform if field == ‘all’, applies to all plots.
- hide_axes(field=None, draw_frame=None)¶
Hides the axes for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object.
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to hide the axes.
draw_frame (boolean) – If True, the axes frame will still be drawn. Defaults to False. See note below for more details.
Examples
This will save an image with no axes.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.save()
This will save an image with no axis or colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.hide_colorbar() >>> s.save()
Note
By default, when removing the axes, the patch on which the axes are drawn is disabled, making it impossible to later change e.g. the background colour. To force the axes patch to be displayed while still hiding the axes, set the
draw_frame
keyword argument toTrue
.
- hide_colorbar(field=None)¶
Hides the colorbar for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object.
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to hide the colorbar. If None or ‘all’ is provided, will default to using all fields available for this object.
Examples
This will save an image with no colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_colorbar() >>> s.save()
This will save an image with no axis or colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.hide_colorbar() >>> s.save()
- list_annotations()¶
List the current callbacks for the plot, along with their index. This index can be used with clear_annotations to remove a callback from the current plot.
- pan(deltas)¶
Pan the image by specifying absolute code unit coordinate deltas.
- Parameters:
deltas (Two-element sequence of floats, quantities, or (float, unit)) –
tuples.
(delta_x, delta_y). If a unit is not supplied the unit is assumed to be code_length.
- pan_rel(deltas)¶
Pan the image by specifying relative deltas, to the FOV.
- Parameters:
deltas (sequence of floats) – (delta_x, delta_y) in relative code unit coordinates
- piter(*args, **kwargs)¶
- refresh()¶
- render() None ¶
Render plots. This operation is expensive and usually doesn’t need to be requested explicitly. In most cases, yt handles rendering automatically and delays it as much as possible to avoid redundant calls on each plot modification (e.g. via annotate_* methods).
However, valid use cases of this method include: - fine control of render (and clear) operations when yt plots are combined with plot
customizations other than plot callbacks (annotate_*)
testing
- run_callbacks()¶
- static sanitize_normal_vector(ds, normal) str | ndarray ¶
Return the name of a cartesian axis whener possible, or a 3-element 1D ndarray of float64 in any other valid case. Fail with a descriptive error message otherwise.
- save(name: str | list[str] | tuple[str, ...] | None = None, suffix: str | None = None, mpl_kwargs: dict[str, Any] | None = None)¶
saves the plot to disk.
- Parameters:
name (string or tuple, optional) – The base of the filename. If name is a directory or if name is not set, the filename of the dataset is used. For a tuple, the resulting path will be given by joining the elements of the tuple
suffix (string, optional) – Specify the image type by its suffix. If not specified, the output type will be inferred from the filename. Defaults to ‘.png’.
mpl_kwargs (dict, optional) – A dict of keyword arguments to be passed to matplotlib.
slc.save(mpl_kwargs={"bbox_inches" (>>>)
- set_antialias(aa)¶
Turn antialiasing on or off.
- Parameters:
aa (boolean)
- set_axes_unit(unit_name)¶
Set the unit for display on the x and y axes of the image.
- Parameters:
unit_name (string or two element tuple of strings) – A unit, available for conversion in the dataset, that the image extents will be displayed in. If set to None, any previous units will be reset. If the unit is None, the default is chosen. If unit_name is ‘1’, ‘u’, or ‘unitary’, it will not display the units, and only show the axes name. If unit_name is a tuple, the first element is assumed to be the unit for the x axis and the second element the unit for the y axis.
- Raises:
YTUnitNotRecognized – If the unit is not known, this will be raised.
Examples
>>> from yt import load >>> ds = load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> p = ProjectionPlot(ds, "y", "Density") >>> p.set_axes_unit("kpc")
- set_background_color(field, color=None)¶
set the background color to match provided color
- Parameters:
field (string) – the field to set the colormap if field == ‘all’, applies to all plots.
color (string or RGBA tuple (optional)) – if set, set the background color to this color if unset, background color is set to the bottom value of the color map
- set_buff_size(size)¶
Sets a new buffer size for the fixed resolution buffer
- Parameters:
size (int or two element sequence of ints) – The number of data elements in the buffer on the x and y axes. If a scalar is provided, then the buffer is assumed to be square.
- set_center(new_center, unit='code_length')¶
Sets a new center for the plot window
- Parameters:
new_center (two element sequence of floats) – The coordinates of the new center of the image in the coordinate system defined by the plot axes. If the unit keyword is not specified, the coordinates are assumed to be in code units.
unit (string) – The name of the unit new_center is given in. If new_center is a YTArray or tuple of YTQuantities, this keyword is ignored.
- set_cmap(field, cmap)¶
set the colormap for one of the fields
- Parameters:
field (string) – the field to set the colormap if field == ‘all’, applies to all plots.
cmap (string or tuple) – If a string, will be interpreted as name of the colormap. If a tuple, it is assumed to be of the form (name, type, number) to be used for palettable functionality. (name, type, number, bool) can be used to specify if a reverse colormap is to be used.
- set_colorbar_label(field, label)¶
Sets the colorbar label.
- set_colorbar_minorticks(field, state)¶
turn colorbar minor ticks on or off in the current plot
Displaying minor ticks reduces performance; turn them off using set_colorbar_minorticks(‘all’, False) if drawing speed is a problem.
- Parameters:
field (string) – the field to remove colorbar minorticks if field == ‘all’, applies to all plots.
state (bool) – the state indicating ‘on’ (True) or ‘off’ (False)
- set_figure_size(size)¶
Sets a new figure size for the plot
- Parameters:
size (float, a sequence of two floats, or None) – The size of the figure (in units of inches), including the margins but not the colorbar. If a single float is passed, it’s interpreted as the size along the long axis. Pass None to reset
- set_font(font_dict=None)¶
Set the font and font properties.
- Parameters:
font_dict (dict) –
A dict of keyword parameters to be passed to
matplotlib.font_manager.FontProperties
.Possible keys include:
family - The font family. Can be serif, sans-serif, cursive, ‘fantasy’ or ‘monospace’.
style - The font style. Either normal, italic or oblique.
color - A valid color string like ‘r’, ‘g’, ‘red’, ‘cobalt’, and ‘orange’.
variant - Either normal or small-caps.
size - Either a relative value of xx-small, x-small, small, medium, large, x-large, xx-large or an absolute font size, e.g. 12
stretch - A numeric value in the range 0-1000 or one of ultra-condensed, extra-condensed, condensed, semi-condensed, normal, semi-expanded, expanded, extra-expanded or ultra-expanded
weight - A numeric value in the range 0-1000 or one of ultralight, light, normal, regular, book, medium, roman, semibold, demibold, demi, bold, heavy, extra bold, or black
See the matplotlib font manager API documentation for more details. https://matplotlib.org/stable/api/font_manager_api.html
Notes
Mathtext axis labels will only obey the size and color keyword.
Examples
This sets the font to be 24-pt, blue, sans-serif, italic, and bold-face.
>>> slc = SlicePlot(ds, "x", "Density") >>> slc.set_font( ... { ... "family": "sans-serif", ... "style": "italic", ... "weight": "bold", ... "size": 24, ... "color": "blue", ... } ... )
- set_font_size(size)¶
Set the size of the font used in the plot
This sets the font size by calling the set_font function. See set_font for more font customization options.
- Parameters:
size (float)
inch). (The absolute size of the font in points (1 pt = 1/72)
- set_log(field, log: bool | None = None, *, linthresh: float | unyt_quantity | tuple[float, Unit | str] | Literal['auto'] | None = None, symlog_auto: bool | None = None)¶
set a field to log, linear, or symlog.
Symlog scaling is a combination of linear and log, where from 0 to a threshold value, it operates as linear, and then beyond that it operates as log. Symlog can also work with negative values in log space as well as negative and positive values simultaneously and symmetrically. If symlog scaling is desired, please set log=True and either set symlog_auto=True or select a value for linthresh.
- Parameters:
field (string) – the field to set a transform if field == ‘all’, applies to all plots.
log (boolean, optional) – set log to True for log scaling, False for linear scaling.
linthresh (float, (float, str), unyt_quantity, or 'auto', optional) – when using symlog scaling, linthresh is the value at which scaling transitions from linear to logarithmic. linthresh must be positive. Note: setting linthresh will automatically enable symlog scale
arguments (Note that log and linthresh are mutually exclusive)
- set_minorticks(field, state)¶
Turn minor ticks on or off in the current plot.
Displaying minor ticks reduces performance; turn them off using set_minorticks(‘all’, False) if drawing speed is a problem.
- Parameters:
field (string) – the field to remove minorticks if field == ‘all’, applies to all plots.
state (bool) – the state indicating ‘on’ (True) or ‘off’ (False)
- set_mpl_projection(mpl_proj)¶
Set the matplotlib projection type with a cartopy transform function
Given a string or a tuple argument, this will project the data onto the plot axes with the chosen transform function.
Assumes that the underlying data has a PlateCarree transform type.
To annotate the plot with coastlines or other annotations, render() will need to be called after this function to make the axes available for annotation.
- Parameters:
mpl_proj (string or tuple) – if passed as a string, mpl_proj is the specified projection type, if passed as a tuple, then tuple will take the form of
("ProjectionType", (args))
or("ProjectionType", (args), {kwargs})
Valid projection type options include: ‘PlateCarree’, ‘LambertConformal’, ‘LabmbertCylindrical’, ‘Mercator’, ‘Miller’, ‘Mollweide’, ‘Orthographic’, ‘Robinson’, ‘Stereographic’, ‘TransverseMercator’, ‘InterruptedGoodeHomolosine’, ‘RotatedPole’, ‘OGSB’, ‘EuroPP’, ‘Geostationary’, ‘Gnomonic’, ‘NorthPolarStereo’, ‘OSNI’, ‘SouthPolarStereo’, ‘AlbersEqualArea’, ‘AzimuthalEquidistant’, ‘Sinusoidal’, ‘UTM’, ‘NearsidePerspective’, ‘LambertAzimuthalEqualArea’
Examples
This will create a Mollweide projection using Mollweide default values and annotate it with coastlines
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection("AIRDENS", "Mollweide") >>> p.render() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will move the PlateCarree central longitude to 90 degrees and annotate with coastlines.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection( ... "AIRDENS", ("PlateCarree", (), {"central_longitude": 90, "globe": None}) ... ) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will create a RoatatedPole projection with the unrotated pole position at 37.5 degrees latitude and 177.5 degrees longitude by passing them in as args.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection("RotatedPole", (177.5, 37.5)) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will create a RoatatedPole projection with the unrotated pole position at 37.5 degrees latitude and 177.5 degrees longitude by passing them in as kwargs.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection( ... ("RotatedPole", (), {"pole_latitude": 37.5, "pole_longitude": 177.5}) ... ) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
- set_norm(field, norm: Normalize)¶
Set a custom
matplotlib.colors.Normalize
to plot field.Any constraints previously set with set_log, set_zlim will be dropped.
Note that any float value attached to norm (e.g. vmin, vmax, vcenter …) will be read in the current displayed units, which can be controlled with the set_unit method.
- Parameters:
field (str or tuple[str, str]) – if field == ‘all’, applies to all plots.
norm (matplotlib.colors.Normalize) – see https://matplotlib.org/stable/tutorials/colors/colormapnorms.html
- set_origin(origin)¶
Set the plot origin.
- Parameters:
origin (string or length 1, 2, or 3 sequence.) – The location of the origin of the plot coordinate system. This is typically represented by a ‘-’ separated string or a tuple of strings. In the first index the y-location is given by ‘lower’, ‘upper’, or ‘center’. The second index is the x-location, given as ‘left’, ‘right’, or ‘center’. Finally, whether the origin is applied in ‘domain’ space, plot ‘window’ space or ‘native’ simulation coordinate system is given. For example, both ‘upper-right-domain’ and [‘upper’, ‘right’, ‘domain’] place the origin in the upper right hand corner of domain space. If x or y are not given, a value is inferred. For instance, ‘left-domain’ corresponds to the lower-left hand corner of the simulation domain, ‘center-domain’ corresponds to the center of the simulation domain, or ‘center-window’ for the center of the plot window. In the event that none of these options place the origin in a desired location, a sequence of tuples and a string specifying the coordinate space can be given. If plain numeric types are input, units of code_length are assumed. Further examples:
=============================== (===============================================)
example (format)
===============================
'domain' ('{space}')
'left-window' ('{xloc}-{space}')
'upper-domain' ('{yloc}-{space}')
'lower-right-window' ('{yloc}-{xloc}-{space}')
('{space}'
('window' ())
)
('{xloc}'
('right' ('{space}'))
'domain')
('{yloc}'
('lower' ('{space}'))
'window')
('{yloc}'
'{xloc}'
('lower'
'right'
'window')
((yloc
'{unit}')
(xloc
'{unit}')
((0 ('{space}'))
'm')
(.4
'm')
'window')
(xloc
yloc
(0.23 ('{space}'))
0.5
'domain')
===============================
- set_unit(field, new_unit, equivalency=None, equivalency_kwargs=None)¶
Sets a new unit for the requested field
- Parameters:
field (string or field tuple) – The name of the field that is to be changed.
new_unit (string or Unit object)
equivalency (string, optional) – If set, the equivalency to use to convert the current units to the new requested unit. If None, the unit conversion will be done without an equivalency
equivalency_kwargs (string, optional) – Keyword arguments to be passed to the equivalency. Only used if
equivalency
is set.
- set_width(width, unit=None)¶
set the width of the plot window
- Parameters:
width (float, array of floats, (float, unit) tuple, or tuple of) –
(float, unit) tuples.
Width can have four different formats to support windows with variable x and y widths. They are:
format
example
(float, string)
(10,’kpc’)
((float, string), (float, string))
((10,’kpc’),(15,’kpc’))
float
0.2
(float, float)
(0.2, 0.3)
For example, (10, ‘kpc’) requests a plot window that is 10 kiloparsecs wide in the x and y directions, ((10,’kpc’),(15,’kpc’)) requests a window that is 10 kiloparsecs wide along the x axis and 15 kiloparsecs wide along the y axis. In the other two examples, code units are assumed, for example (0.2, 0.3) requests a plot that has an x width of 0.2 and a y width of 0.3 in code units. If units are provided the resulting plot axis labels will use the supplied units.
unit (str) – the unit the width has been specified in. If width is a tuple, this argument is ignored. Defaults to code units.
- set_xlabel(label)¶
Allow the user to modify the X-axis title Defaults to the global value. Fontsize defaults to 18.
- Parameters:
label (str) – The new string for the x-axis.
(cm$^{-3}$)") (>>> plot.set_xlabel("H2I Number Density)
- set_ylabel(label)¶
Allow the user to modify the Y-axis title Defaults to the global value.
- Parameters:
label (str) – The new string for the y-axis.
(K)") (>>> plot.set_ylabel("Temperature)
- set_zlim(field, zmin: ~unyt.array.unyt_quantity | tuple[float, ~unyt.unit_object.Unit | str] | float | ~typing.Literal['min'] | ~yt.visualization.plot_container.Unset = <yt.visualization.plot_container.Unset object>, zmax: ~unyt.array.unyt_quantity | tuple[float, ~unyt.unit_object.Unit | str] | float | ~typing.Literal['max'] | ~yt.visualization.plot_container.Unset = <yt.visualization.plot_container.Unset object>, dynamic_range: float | None = None)¶
set the scale of the colormap
- Parameters:
field (string) – the field to set a colormap scale if field == ‘all’, applies to all plots.
zmin (float, Quantity, or 'min') – the new minimum of the colormap scale. If ‘min’, will set to the minimum value in the current view.
zmax (float, Quantity, or 'max') – the new maximum of the colormap scale. If ‘max’, will set to the maximum value in the current view.
dynamic_range (float (default: None)) – The dynamic range of the image. If zmin == None, will set zmin = zmax / dynamic_range If zmax == None, will set zmax = zmin * dynamic_range
- setup_callbacks()¶
- show()¶
This will send any existing plots to the IPython notebook.
If yt is being run from within an IPython session, and it is able to determine this, this function will send any existing plots to the notebook for display.
If yt can’t determine if it’s inside an IPython session, it will raise YTNotInsideNotebook.
Examples
>>> from yt import SlicePlot >>> slc = SlicePlot( ... ds, "x", [("gas", "density"), ("gas", "velocity_magnitude")] ... ) >>> slc.show()
- show_axes(field=None)¶
Shows the axes for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object. See hide_axes().
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to show the axes.
- show_colorbar(field=None)¶
Shows the colorbar for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object. See hide_colorbar().
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional))
colorbar. (The name of the field(s) that we want to show the)
- swap_axes()¶
- to_fits_data(fields=None, other_keys=None, length_unit=None, **kwargs)¶
Export the fields in this PlotWindow instance to a FITSImageData instance.
This will export a set of FITS images of either the fields specified or all the fields already in the object.
- Parameters:
fields (list of strings) – These fields will be pixelized and output. If “None”, the keys of the FRB will be used.
other_keys (dictionary, optional) – A set of header keys and values to write into the FITS header.
length_unit (string, optional) – the length units that the coordinates are written in. The default is to use the default length unit of the dataset.
- property width¶
- class yt.visualization.plot_window.OffAxisSlicePlot(ds, normal, fields, *args, **kwargs)[source]¶
Bases:
SlicePlot
,PWViewerMPL
Creates an off axis slice plot from a dataset
Given a ds object, a normal vector defining a slicing plane, and a field name string, this will return a PWViewerMPL object containing the plot.
The plot can be updated using one of the many helper functions defined in PlotWindow.
- Parameters:
ds (
yt.data_objects.static_output.Dataset
) – This is the dataset object corresponding to the simulation output to be plotted.normal (a sequence of floats) – The vector normal to the slicing plane.
fields (string) – The name of the field(s) to be plotted.
center ('center', 'c' id of a global extremum, or array-like) –
The coordinate of the selection’s center. Defaults to the ‘center’, i.e. center of the domain.
Centering on the min or max of a field is supported by passing a tuple such as (‘min’, (‘gas’, ‘density’)) or (‘max’, (‘gas’, ‘temperature’). A single string may also be used (e.g. “min_density” or “max_temperature”), though it’s not as flexible and does not allow to select an exact field/particle type. With this syntax, the first field matching the provided name is selected. ‘max’ or ‘m’ can be used as a shortcut for (‘max’, (‘gas’, ‘density’)) ‘min’ can be used as a shortcut for (‘min’, (‘gas’, ‘density’))
One can also select an exact point as a 3 element coordinate sequence, e.g. [0.5, 0.5, 0] Units can be specified by passing in center as a tuple containing a 3-element coordinate sequence and string unit name, e.g. ([0, 0.5, 0.5], “cm”), or by passing in a YTArray. Code units are assumed if unspecified.
width (tuple or a float.) –
Width can have four different formats to support windows with variable x and y widths. They are:
format
example
(float, string)
(10,’kpc’)
((float, string), (float, string))
((10,’kpc’),(15,’kpc’))
float
0.2
(float, float)
(0.2, 0.3)
For example, (10, ‘kpc’) requests a plot window that is 10 kiloparsecs wide in the x and y directions, ((10,’kpc’),(15,’kpc’)) requests a window that is 10 kiloparsecs wide along the x axis and 15 kiloparsecs wide along the y axis. In the other two examples, code units are assumed, for example (0.2, 0.3) requests a plot that has an x width of 0.2 and a y width of 0.3 in code units. If units are provided the resulting plot axis labels will use the supplied units.
axes_unit (string) – The name of the unit for the tick labels on the x and y axes. Defaults to None, which automatically picks an appropriate unit. If axes_unit is ‘1’, ‘u’, or ‘unitary’, it will not display the units, and only show the axes name.
north_vector (a sequence of floats) – A vector defining the ‘up’ direction in the plot. This option sets the orientation of the slicing plane. If not set, an arbitrary grid-aligned north-vector is chosen.
fontsize (integer) – The size of the fonts for the axis, colorbar, and tick labels.
field_parameters (dictionary) – A dictionary of field parameters than can be accessed by derived fields.
data_source (YTSelectionContainer Object) – Object to be used for data selection. Defaults ds.all_data(), a region covering the full domain.
buff_size (length 2 sequence) – Size of the buffer to use for the image, i.e. the number of resolution elements used. Effectively sets a resolution limit to the image if buff_size is smaller than the finest gridding.
- annotate_arrow(pos, *, length=0.03, width=0.0001, head_width=0.01, head_length=0.01, starting_pos=None, coord_system='data', plot_args: dict[str, Any] | None = None, **kwargs)¶
Overplot arrow(s) pointing at position(s) for highlighting specific features. By default, arrow points from lower left to the designated position “pos” with arrow length “length”. Alternatively, if “starting_pos” is set, arrow will stretch from “starting_pos” to “pos” and “length” will be disregarded.
“coord_system” keyword refers to positions set in “pos” arg and “starting_pos” keyword, which by default are in data coordinates.
“length”, “width”, “head_length”, and “head_width” keywords for the arrow are all in axis units, ie relative to the size of the plot axes as 1, even if the position of the arrow is set relative to another coordinate system.
- Parameters:
pos (array-like) – These are the coordinates where the marker(s) will be overplotted Either as [x,y,z] or as [[x1,x2,…],[y1,y2,…],[z1,z2,…]]
length (float, optional) – The length, in axis units, of the arrow. Default: 0.03
width (float, optional) – The width, in axis units, of the tail line of the arrow. Default: 0.003
head_length (float, optional) – The length, in axis units, of the head of the arrow. If set to None, use 1.5*head_width Default: None
head_width (float, optional) – The width, in axis units, of the head of the arrow. Default: 0.02
starting_pos (2- or 3-element tuple, list, or array, optional) – These are the coordinates from which the arrow starts towards its point. Not compatible with ‘length’ kwarg.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
plot_args (dictionary, optional) – This dictionary is passed to the MPL arrow function for generating the arrow. By default, it is: {‘color’:’white’}
Examples
>>> # Overplot an arrow pointing to feature at data coord: (0.2, 0.3, 0.4) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_arrow([0.2, 0.3, 0.4]) >>> s.save()
>>> # Overplot a red arrow with longer length pointing to plot coordinate >>> # (0.1, -0.1) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_arrow( ... [0.1, -0.1], length=0.06, coord_system="plot", color="red" ... ) >>> s.save()
- annotate_cell_edges(line_width=0.002, alpha=1.0, color='black')¶
Annotate cell edges. This is done through a second call to pixelize, where the distance from a pixel to a cell boundary in pixels is compared against the line_width argument. The secondary image is colored as color and overlaid with the alpha value.
- Parameters:
line_width (float) – The width of the cell edge lines in normalized units relative to the size of the longest axis. Default is 1% of the size of the smallest axis.
alpha (float) – When the second image is overlaid, it will have this level of alpha transparency. Default is 1.0 (fully-opaque).
color (tuple of three floats or matplotlib color name) – This is the color of the cell edge values. It defaults to black.
Examples
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_cell_edges() >>> s.save()
- annotate_clumps(clumps, *, plot_args=None, **kwargs)¶
Take a list of clumps and plot them as a set of contours.
- annotate_contour(field: tuple[str, str] | str, levels: int = 5, *, factor: tuple[int, int] | int = 4, clim: tuple[float, float] | None = None, label: bool = False, take_log: bool | None = None, data_source: YTDataContainer | None = None, plot_args: dict[str, Any] | None = None, text_args: dict[str, Any] | None = None, ncont: int | None = None) None ¶
Add contours in field to the plot. levels governs the number of contours generated, factor governs the number of points used in the interpolation, take_log governs how it is contoured and clim gives the (lower, upper) limits for contouring. An alternate data source can be specified with data_source, but by default the plot’s data source will be queried.
- annotate_cquiver(field_x, field_y, field_c=None, *, factor: tuple[int, int] | int = 16, scale=None, scale_units=None, normalize=False, plot_args=None, **kwargs)¶
Get a quiver plot on top of a cutting plane, using field_x and field_y, skipping every factor datapoint in the discretization. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- annotate_grids(alpha=0.7, min_pix=1, min_pix_ids=20, draw_ids=False, id_loc=None, periodic=True, min_level=None, max_level=None, cmap='B-W LINEAR_r', edgecolors=None, linewidth=1.0)¶
Draws grids on an existing PlotWindow object. Adds grid boundaries to a plot, optionally with alpha-blending. By default, colors different levels of grids with different colors going from white to black, but you can change to any arbitrary colormap with cmap keyword, to all black grid edges for all levels with cmap=None and edgecolors=None, or to an arbitrary single color for grid edges with edgecolors=’YourChosenColor’ defined in any of the standard ways (e.g., edgecolors=’white’, edgecolors=’r’, edgecolors=’#00FFFF’, or edgecolor=’0.3’, where the last is a float in 0-1 scale indicating gray). Note that setting edgecolors overrides cmap if you have both set to non-None values. Cutoff for display is at min_pix wide. draw_ids puts the grid id a the corner of the grid (but its not so great in projections…). id_loc determines which corner holds the grid id. One can set min and maximum level of grids to display, and can change the linewidth of the displayed grids.
- annotate_line(p1, p2, *, coord_system='data', plot_args: dict[str, Any] | None = None, **kwargs)¶
Overplot a line with endpoints at p1 and p2. p1 and p2 should be 2D or 3D coordinates consistent with the coordinate system denoted in the “coord_system” keyword.
- Parameters:
p1 (2- or 3-element tuples, lists, or arrays) – These are the coordinates of the endpoints of the line.
p2 (2- or 3-element tuples, lists, or arrays) – These are the coordinates of the endpoints of the line.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates p1 and p2. Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
plot_args (dictionary, optional) – This dictionary is passed to the MPL plot function for generating the line. By default, it is: {‘color’:’white’, ‘linewidth’:2}
Examples
>>> # Overplot a diagonal white line from the lower left corner to upper >>> # right corner >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_line([0, 0], [1, 1], coord_system="axis") >>> s.save()
>>> # Overplot a red dashed line from data coordinate (0.1, 0.2, 0.3) to >>> # (0.5, 0.6, 0.7) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_line( ... [0.1, 0.2, 0.3], ... [0.5, 0.6, 0.7], ... coord_system="data", ... color="red", ... linestyles="--", ... ) >>> s.save()
- annotate_line_integral_convolution(field_x, field_y, texture=None, kernellen=50.0, lim=(0.5, 0.6), cmap='binary', alpha=0.8, const_alpha=False)¶
Add the line integral convolution to the plot for vector fields visualization. Two component of vector fields needed to be provided (i.e., velocity_x and velocity_y, magnetic_field_x and magnetic_field_y).
- Parameters:
field_x (string) – The names of two components of vector field which will be visualized
field_y (string) – The names of two components of vector field which will be visualized
texture (2-d array with the same shape of image, optional) – Texture will be convolved when computing line integral convolution. A white noise background will be used as default.
kernellen (float, optional) – The lens of kernel for convolution, which is the length over which the convolution will be performed. For longer kernellen, longer streamline structure will appear.
lim (2-element tuple, list, or array, optional) – The value of line integral convolution will be clipped to the range of lim, which applies upper and lower bounds to the values of line integral convolution and enhance the visibility of plots. Each element should be in the range of [0,1].
cmap (string, optional) – The name of colormap for line integral convolution plot.
alpha (float, optional) – The alpha value for line integral convolution plot.
const_alpha (boolean, optional) – If set to False (by default), alpha will be weighted spatially by the values of line integral convolution; otherwise a constant value of the given alpha is used.
Example
>>> import yt >>> ds = yt.load("Enzo_64/DD0020/data0020") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_line_integral_convolution( ... "velocity_x", "velocity_y", lim=(0.5, 0.65) ... )
- annotate_magnetic_field(factor: tuple[int, int] | int = 16, *, scale=None, scale_units=None, normalize=False, plot_args=None, **kwargs)¶
Adds a ‘quiver’ plot of magnetic field to the plot, skipping all but every factor datapoint. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the magnetic fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- annotate_marker(pos, marker='x', *, coord_system='data', plot_args=None, **kwargs)¶
Overplot marker(s) at a position(s) for highlighting specific features.
- Parameters:
pos (array-like) – These are the coordinates where the marker(s) will be overplotted Either as [x,y,z] or as [[x1,x2,…],[y1,y2,…],[z1,z2,…]]
marker (string, optional) – The shape of the marker to be passed to the MPL scatter function. By default, it is ‘x’, but other acceptable values are: ‘.’, ‘o’, ‘v’, ‘^’, ‘s’, ‘p’ ‘*’, etc. See matplotlib.markers for more information.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
plot_args (dictionary, optional) – This dictionary is passed to the MPL scatter function for generating the marker. By default, it is: {‘color’:’white’, ‘s’:50}
Examples
>>> # Overplot a white X on a feature at data location (0.5, 0.5, 0.5) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_marker([0.4, 0.5, 0.6]) >>> s.save()
>>> # Overplot a big yellow circle at axis location (0.1, 0.2) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_marker( ... [0.1, 0.2], ... marker="o", ... coord_system="axis", ... color="yellow", ... s=200, ... ) >>> s.save()
- annotate_mesh_lines(*, plot_args=None, **kwargs)¶
Adds mesh lines to the plot. Only works for unstructured or semi-structured mesh data. For structured grid data, see GridBoundaryCallback or CellEdgesCallback.
- Parameters:
plot_args (dict, optional) – A dictionary of arguments that will be passed to matplotlib.
Example
>>> import yt >>> ds = yt.load("MOOSE_sample_data/out.e-s010") >>> sl = yt.SlicePlot(ds, "z", ("connect2", "convected")) >>> sl.annotate_mesh_lines(color="black")
- annotate_particles(width, p_size=1.0, col='k', marker='o', stride=1, ptype='all', alpha=1.0, data_source=None)¶
Adds particle positions, based on a thick slab along axis with a width along the line of sight. p_size controls the number of pixels per particle, and col governs the color. ptype will restrict plotted particles to only those that are of a given type. alpha determines the opacity of the marker symbol used in the scatter. An alternate data source can be specified with data_source, but by default the plot’s data source will be queried.
- annotate_quiver(field_x, field_y, field_c=None, *, factor: tuple[int, int] | int = 16, scale=None, scale_units=None, normalize=False, bv_x=0, bv_y=0, plot_args=None, **kwargs)¶
Adds a ‘quiver’ plot to any plot, using the field_x and field_y from the associated data, skipping every factor pixels. field_c is an optional field name used for color. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- annotate_ray(ray, *, arrow=False, plot_args=None, **kwargs)¶
Adds a line representing the projected path of a ray across the plot. The ray can be either a YTOrthoRay, YTRay, or a LightRay object. annotate_ray() will properly account for periodic rays across the volume. If arrow is set to True, uses the MPL.pyplot.arrow function, otherwise uses the MPL.pyplot.plot function to plot a normal line. Adjust plot_args accordingly.
- Parameters:
ray (YTOrthoRay, YTRay, or LightRay) – Ray is the object that we want to include. We overplot the projected trajectory of the ray. If the object is a trident.LightRay object, it will only plot the segment of the LightRay that intersects the dataset currently displayed.
arrow (boolean, optional) – Whether or not to place an arrowhead on the front of the ray to denote direction Default: False
plot_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib line object. Defaults: {‘color’:’white’, ‘linewidth’:2}.
Examples
>>> # Overplot a ray and an ortho_ray object on a projection >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> oray = ds.ortho_ray(1, (0.3, 0.4)) # orthoray down the y axis >>> ray = ds.ray((0.1, 0.2, 0.3), (0.6, 0.7, 0.8)) # arbitrary ray >>> p = yt.ProjectionPlot(ds, "z", "density") >>> p.annotate_ray(oray) >>> p.annotate_ray(ray) >>> p.save()
>>> # Overplot a LightRay object on a projection >>> import yt >>> from trident import LightRay >>> ds = yt.load("enzo_cosmology_plus/RD0004/RD0004") >>> lr = LightRay( ... "enzo_cosmology_plus/AMRCosmology.enzo", "Enzo", 0.0, 0.1, time_data=False ... ) >>> lray = lr.make_light_ray(seed=1) >>> p = yt.ProjectionPlot(ds, "z", "density") >>> p.annotate_ray(lr) >>> p.save()
- annotate_scale(*, corner='lower_right', coeff=None, unit=None, pos=None, max_frac=0.16, min_frac=0.015, coord_system='axis', text_args=None, size_bar_args=None, draw_inset_box=False, inset_box_args=None, scale_text_format='{scale} {units}')¶
Annotates the scale of the plot at a specified location in the image (either in a preset corner, or by specifying (x,y) image coordinates with the pos argument. Coeff and units (e.g. 1 Mpc or 100 kpc) refer to the distance scale you desire to show on the plot. If no coeff and units are specified, an appropriate pair will be determined such that your scale bar is never smaller than min_frac or greater than max_frac of your plottable axis length. Additional customization of the scale bar is possible by adjusting the text_args and size_bar_args dictionaries. The text_args dictionary accepts matplotlib’s font_properties arguments to override the default font_properties for the current plot. The size_bar_args dictionary accepts keyword arguments for the AnchoredSizeBar class in matplotlib’s axes_grid toolkit.
- Parameters:
corner (string, optional) – Corner sets up one of 4 predeterimined locations for the scale bar to be displayed in the image: ‘upper_left’, ‘upper_right’, ‘lower_left’, ‘lower_right’ (also allows None). This value will be overridden by the optional ‘pos’ keyword.
coeff (float, optional) – The coefficient of the unit defining the distance scale (e.g. 10 kpc or 100 Mpc) for overplotting. If set to None along with unit keyword, coeff will be automatically determined to be a power of 10 relative to the best-fit unit.
unit (string, optional) – unit must be a valid yt distance unit (e.g. ‘m’, ‘km’, ‘AU’, ‘pc’, ‘kpc’, etc.) or set to None. If set to None, will be automatically determined to be the best-fit to the data.
pos (2- or 3-element tuples, lists, or arrays, optional) – The image location of the scale bar in the plot coordinate system. Setting pos overrides the corner parameter.
min_frac (float, optional) – The minimum/maximum fraction of the axis width for the scale bar to extend. A value of 1 would allow the scale bar to extend across the entire axis width. Only used for automatically calculating best-fit coeff and unit when neither is specified, otherwise disregarded.
max_frac (float, optional) – The minimum/maximum fraction of the axis width for the scale bar to extend. A value of 1 would allow the scale bar to extend across the entire axis width. Only used for automatically calculating best-fit coeff and unit when neither is specified, otherwise disregarded.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data”: 3D dataset coordinates
”plot”: 2D coordinates defined by the actual plot limits
”axis”: MPL axis coordinates: (0,0) is lower left; (1,1) is upper right
”figure”: MPL figure coordinates: (0,0) is lower left, (1,1) is upper right
text_args (dictionary, optional) – A dictionary of parameters to used to update the font_properties for the text in this callback. For any property not set, it will use the defaults of the plot. Thus one can modify the text size with
text_args={'size':24}
size_bar_args (dictionary, optional) – A dictionary of parameters to be passed to the Matplotlib AnchoredSizeBar initializer. Defaults:
{'pad': 0.25, 'sep': 5, 'borderpad': 1, 'color': 'w'}
draw_inset_box (boolean, optional) – Whether or not an inset box should be included around the scale bar.
inset_box_args (dictionary, optional) – A dictionary of keyword arguments to be passed to the matplotlib Patch object that represents the inset box. Defaults:
{'facecolor': 'black', 'linewidth': 3, 'edgecolor': 'white', 'alpha': 0.5, 'boxstyle': 'square'}
scale_text_format (string, optional) – This specifies the format of the scalebar value assuming “scale” is the numerical value and “unit” is units of the scale (e.g. ‘cm’, ‘kpc’, etc.) The scale can be specified to arbitrary precision according to printf formatting codes. The format string must only specify “scale” and “units”. Example: “Length = {scale:.2f} {units}”. Default: “{scale} {units}”
Example
>>> import yt >>> ds = yt.load("Enzo_64/DD0020/data0020") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_scale()
- annotate_sphere(center, radius, *, coord_system='data', text=None, circle_args=None, text_args=None)¶
Overplot a circle with designated center and radius with optional text.
- Parameters:
center (2- or 3-element tuple, list, or array) – These are the coordinates where the circle will be overplotted
radius (YTArray, float, or (1, ('kpc')) style tuple) – The radius of the circle in code coordinates
circle_args (dict, optional) – This dictionary is passed to the MPL circle object. By default, {‘color’:’white’}
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
text (string, optional) – Optional text to include next to the circle.
text_args (dictionary, optional) – This dictionary is passed to the MPL text function. By default, it is: {‘color’:’white’}
Examples
>>> # Overplot a white circle of radius 100 kpc over the central galaxy >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_sphere([0.5, 0.5, 0.5], radius=(100, "kpc")) >>> s.save()
- annotate_streamlines(field_x: tuple[str, str] | str, field_y: tuple[str, str] | str, *, linewidth: float | tuple[str, str] | str = 1.0, linewidth_upscaling: float = 1.0, color: Any | tuple[str, str] | None = None, color_threshold: float | unyt_quantity = -inf, factor: tuple[int, int] | int = 16, field_color=None, display_threshold=None, plot_args=None, **kwargs)¶
Plot streamlines using matplotlib.axes.Axes.streamplot
- Parameters:
field_x (field key) – The “velocity” analoguous field along the horizontal direction.
field_y (field key) – The “velocity” analoguous field along the vertical direction.
linewidth (float, or field key (default: 1.0)) – A constant scalar will be passed directly to matplotlib.axes.Axes.streamplot A field key will be first interpreted by yt and produce the adequate 2D array. Data fields are normalized by their maximum value, so the maximal linewidth is 1 by default. See linewidth_upscaling for fine tuning. Note that the absolute value is taken in all cases.
linewidth_upscaling (float (default: 1.0)) – A constant multiplicative factor applied to linewidth. Final linewidth is obtained as: linewidth_upscaling * abs(linewidth) / max(abs(linewidth))
color (a color identifier, or a field key (default: matplotlib.rcParams['line.color'])) – A constant color identifier will be passed directly to matplotlib.axes.Axes.streamplot A field key will be first interpreted by yt and produce the adequate 2D array. See https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.streamplot.html for how to customize color mapping using cmap and norm arguments.
color_threshold (float or unyt_quantity (default: -inf)) – Regions where the field used for color is lower than this threshold will be masked. Only used if color is a field key.
factor (int, or tuple[int, int] (default: 16)) – Fields are downed-sampled by this factor with respect to the background image buffer size. A single integer factor will be used for both direction, but a tuple of 2 integers can be passed to set x and y downsampling independently.
**kwargs (any additional keyword arguments will be passed) – directly to matplotlib.axes.Axes.streamplot
- annotate_text(pos, text, *, coord_system='data', text_args=None, inset_box_args=None)¶
Overplot text on the plot at a specified position. If you desire an inset box around your text, set one with the inset_box_args dictionary keyword.
- Parameters:
pos (2- or 3-element tuple, list, or array) – These are the coordinates where the text will be overplotted
text (string) – The text you wish to include
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
text_args (dictionary, optional) – This dictionary is passed to the MPL text function for generating the text. By default, it is: {‘color’:’white’} and uses the defaults for the other fonts in the image.
inset_box_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib FancyBboxPatch object as the inset box around the text. Default: {}
Examples
>>> # Overplot white text at data location [0.55, 0.7, 0.4] >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_text([0.55, 0.7, 0.4], "Here is a galaxy") >>> s.save()
>>> # Overplot yellow text at axis location [0.2, 0.8] with >>> # a shaded inset box >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_text( ... [0.2, 0.8], ... "Here is a galaxy", ... coord_system="axis", ... text_args={"color": "yellow"}, ... inset_box_args={ ... "boxstyle": "square,pad=0.3", ... "facecolor": "black", ... "linewidth": 3, ... "edgecolor": "white", ... "alpha": 0.5, ... }, ... ) >>> s.save()
- annotate_timestamp(x_pos=None, y_pos=None, corner='lower_left', *, time=True, redshift=False, time_format='t = {time:.1f} {units}', time_unit=None, redshift_format='z = {redshift:.2f}', draw_inset_box=False, coord_system='axis', time_offset=None, text_args=None, inset_box_args=None)¶
Annotates the timestamp and/or redshift of the data output at a specified location in the image (either in a present corner, or by specifying (x,y) image coordinates with the x_pos, y_pos arguments. If no time_units are specified, it will automatically choose appropriate units. It allows for custom formatting of the time and redshift information, as well as the specification of an inset box around the text.
- Parameters:
x_pos (floats, optional) – The image location of the timestamp in the coord system defined by the coord_system kwarg. Setting x_pos and y_pos overrides the corner parameter.
y_pos (floats, optional) – The image location of the timestamp in the coord system defined by the coord_system kwarg. Setting x_pos and y_pos overrides the corner parameter.
corner (string, optional) – Corner sets up one of 4 predeterimined locations for the timestamp to be displayed in the image: ‘upper_left’, ‘upper_right’, ‘lower_left’, ‘lower_right’ (also allows None). This value will be overridden by the optional x_pos and y_pos keywords.
time (boolean, optional) – Whether or not to show the ds.current_time of the data output. Can be used solo or in conjunction with redshift parameter.
redshift (boolean, optional) – Whether or not to show the ds.current_time of the data output. Can be used solo or in conjunction with the time parameter.
time_format (string, optional) – This specifies the format of the time output assuming “time” is the number of time and “unit” is units of the time (e.g. ‘s’, ‘Myr’, etc.) The time can be specified to arbitrary precision according to printf formatting codes (defaults to .1f – a float with 1 digits after decimal). Example: “Age = {time:.2f} {units}”.
time_unit (string, optional) – time_unit must be a valid yt time unit (e.g. ‘s’, ‘min’, ‘hr’, ‘yr’, ‘Myr’, etc.)
redshift_format (string, optional) – This specifies the format of the redshift output. The redshift can be specified to arbitrary precision according to printf formatting codes (defaults to 0.2f – a float with 2 digits after decimal). Example: “REDSHIFT = {redshift:03.3g}”,
draw_inset_box (boolean, optional) – Whether or not an inset box should be included around the text If so, it uses the inset_box_args to set the matplotlib FancyBboxPatch object.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data”: 3D dataset coordinates
”plot”: 2D coordinates defined by the actual plot limits
”axis”: MPL axis coordinates: (0,0) is lower left; (1,1) is upper right
”figure”: MPL figure coordinates: (0,0) is lower left, (1,1) is upper right
time_offset (float, (value, unit) tuple, or YTQuantity, optional) – Apply an offset to the time shown in the annotation from the value of the current time. If a scalar value with no units is passed in, the value of the time_unit kwarg is used for the units. Default: None, meaning no offset.
text_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib text object. Defaults:
{'color':'white', 'horizontalalignment':'center', 'verticalalignment':'top'}
.inset_box_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib FancyBboxPatch object as the inset box around the text. Defaults:
{'boxstyle':'square', 'pad':0.3, 'facecolor':'black', 'linewidth':3, 'edgecolor':'white', 'alpha':0.5}
Example
>>> import yt >>> ds = yt.load("Enzo_64/DD0020/data0020") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_timestamp()
- annotate_title(title)¶
Accepts a title and adds it to the plot
- annotate_triangle_facets(triangle_vertices, *, plot_args=None, **kwargs)¶
Intended for representing a slice of a triangular faceted geometry in a slice plot.
Uses a set of triangle_vertices to find all triangles the plane of a SlicePlot intersects with. The lines between the intersection points of the triangles are then added to the plot to create an outline of the geometry represented by the triangles.
- annotate_velocity(factor: tuple[int, int] | int = 16, *, scale=None, scale_units=None, normalize=False, plot_args=None, **kwargs)¶
Adds a ‘quiver’ plot of velocity to the plot, skipping all but every factor datapoint. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the velocity fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- property bounds¶
- clear_annotations(index: int | None = None)¶
Clear callbacks from the plot. If index is not set, clear all callbacks. If index is set, clear that index (ie 0 is the first one created, 1 is the 2nd one created, -1 is the last one created, etc.)
- display(name=None, mpl_kwargs=None)¶
Will attempt to show the plot in in an IPython notebook. Failing that, the plot will be saved to disk.
- export_to_mpl_figure(nrows_ncols, axes_pad=1.0, label_mode='L', cbar_location='right', cbar_size='5%', cbar_mode='each', cbar_pad='0%')¶
Creates a matplotlib figure object with the specified axes arrangement, nrows_ncols, and maps the underlying figures to the matplotlib axes. Note that all of these parameters are fed directly to the matplotlib ImageGrid class to create the new figure layout.
- Parameters:
nrows_ncols (tuple) – the number of rows and columns of the axis grid (e.g., nrows_ncols=(2,2,))
axes_pad (float) – padding between axes in inches
label_mode (one of "L", "1", "all") – arrangement of axes that are labeled
cbar_location (one of "left", "right", "bottom", "top") – where to place the colorbar
cbar_size (string (percentage)) – scaling of the colorbar (e.g., “5%”)
cbar_mode (one of "each", "single", "edge", None) – how to represent the colorbar
cbar_pad (string (percentage)) – padding between the axis and colorbar (e.g. “5%”)
- Return type:
The return is a matplotlib figure object.
Examples
>>> import yt >>> ds = yt.load_sample("IsolatedGalaxy") >>> fields = ["density", "velocity_x", "velocity_y", "velocity_magnitude"] >>> p = yt.SlicePlot(ds, "z", fields) >>> p.set_log("velocity_x", False) >>> p.set_log("velocity_y", False) >>> fig = p.export_to_mpl_figure((2, 2)) >>> fig.tight_layout() >>> fig.savefig("test.png")
- flip_horizontal()¶
inverts the horizontal axis (the image’s abscissa)
- flip_vertical()¶
inverts the vertical axis (the image’s ordinate)
- property frb¶
- get_log(field)¶
get the transform type of a field.
- Parameters:
field (string) – the field to get a transform if field == ‘all’, applies to all plots.
- hide_axes(field=None, draw_frame=None)¶
Hides the axes for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object.
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to hide the axes.
draw_frame (boolean) – If True, the axes frame will still be drawn. Defaults to False. See note below for more details.
Examples
This will save an image with no axes.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.save()
This will save an image with no axis or colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.hide_colorbar() >>> s.save()
Note
By default, when removing the axes, the patch on which the axes are drawn is disabled, making it impossible to later change e.g. the background colour. To force the axes patch to be displayed while still hiding the axes, set the
draw_frame
keyword argument toTrue
.
- hide_colorbar(field=None)¶
Hides the colorbar for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object.
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to hide the colorbar. If None or ‘all’ is provided, will default to using all fields available for this object.
Examples
This will save an image with no colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_colorbar() >>> s.save()
This will save an image with no axis or colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.hide_colorbar() >>> s.save()
- list_annotations()¶
List the current callbacks for the plot, along with their index. This index can be used with clear_annotations to remove a callback from the current plot.
- pan(deltas)¶
Pan the image by specifying absolute code unit coordinate deltas.
- Parameters:
deltas (Two-element sequence of floats, quantities, or (float, unit)) –
tuples.
(delta_x, delta_y). If a unit is not supplied the unit is assumed to be code_length.
- pan_rel(deltas)¶
Pan the image by specifying relative deltas, to the FOV.
- Parameters:
deltas (sequence of floats) – (delta_x, delta_y) in relative code unit coordinates
- piter(*args, **kwargs)¶
- refresh()¶
- render() None ¶
Render plots. This operation is expensive and usually doesn’t need to be requested explicitly. In most cases, yt handles rendering automatically and delays it as much as possible to avoid redundant calls on each plot modification (e.g. via annotate_* methods).
However, valid use cases of this method include: - fine control of render (and clear) operations when yt plots are combined with plot
customizations other than plot callbacks (annotate_*)
testing
- run_callbacks()¶
- static sanitize_normal_vector(ds, normal) str | ndarray ¶
Return the name of a cartesian axis whener possible, or a 3-element 1D ndarray of float64 in any other valid case. Fail with a descriptive error message otherwise.
- save(name: str | list[str] | tuple[str, ...] | None = None, suffix: str | None = None, mpl_kwargs: dict[str, Any] | None = None)¶
saves the plot to disk.
- Parameters:
name (string or tuple, optional) – The base of the filename. If name is a directory or if name is not set, the filename of the dataset is used. For a tuple, the resulting path will be given by joining the elements of the tuple
suffix (string, optional) – Specify the image type by its suffix. If not specified, the output type will be inferred from the filename. Defaults to ‘.png’.
mpl_kwargs (dict, optional) – A dict of keyword arguments to be passed to matplotlib.
slc.save(mpl_kwargs={"bbox_inches" (>>>)
- set_antialias(aa)¶
Turn antialiasing on or off.
- Parameters:
aa (boolean)
- set_axes_unit(unit_name)¶
Set the unit for display on the x and y axes of the image.
- Parameters:
unit_name (string or two element tuple of strings) – A unit, available for conversion in the dataset, that the image extents will be displayed in. If set to None, any previous units will be reset. If the unit is None, the default is chosen. If unit_name is ‘1’, ‘u’, or ‘unitary’, it will not display the units, and only show the axes name. If unit_name is a tuple, the first element is assumed to be the unit for the x axis and the second element the unit for the y axis.
- Raises:
YTUnitNotRecognized – If the unit is not known, this will be raised.
Examples
>>> from yt import load >>> ds = load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> p = ProjectionPlot(ds, "y", "Density") >>> p.set_axes_unit("kpc")
- set_background_color(field, color=None)¶
set the background color to match provided color
- Parameters:
field (string) – the field to set the colormap if field == ‘all’, applies to all plots.
color (string or RGBA tuple (optional)) – if set, set the background color to this color if unset, background color is set to the bottom value of the color map
- set_buff_size(size)¶
Sets a new buffer size for the fixed resolution buffer
- Parameters:
size (int or two element sequence of ints) – The number of data elements in the buffer on the x and y axes. If a scalar is provided, then the buffer is assumed to be square.
- set_center(new_center, unit='code_length')¶
Sets a new center for the plot window
- Parameters:
new_center (two element sequence of floats) – The coordinates of the new center of the image in the coordinate system defined by the plot axes. If the unit keyword is not specified, the coordinates are assumed to be in code units.
unit (string) – The name of the unit new_center is given in. If new_center is a YTArray or tuple of YTQuantities, this keyword is ignored.
- set_cmap(field, cmap)¶
set the colormap for one of the fields
- Parameters:
field (string) – the field to set the colormap if field == ‘all’, applies to all plots.
cmap (string or tuple) – If a string, will be interpreted as name of the colormap. If a tuple, it is assumed to be of the form (name, type, number) to be used for palettable functionality. (name, type, number, bool) can be used to specify if a reverse colormap is to be used.
- set_colorbar_label(field, label)¶
Sets the colorbar label.
- set_colorbar_minorticks(field, state)¶
turn colorbar minor ticks on or off in the current plot
Displaying minor ticks reduces performance; turn them off using set_colorbar_minorticks(‘all’, False) if drawing speed is a problem.
- Parameters:
field (string) – the field to remove colorbar minorticks if field == ‘all’, applies to all plots.
state (bool) – the state indicating ‘on’ (True) or ‘off’ (False)
- set_figure_size(size)¶
Sets a new figure size for the plot
- Parameters:
size (float, a sequence of two floats, or None) – The size of the figure (in units of inches), including the margins but not the colorbar. If a single float is passed, it’s interpreted as the size along the long axis. Pass None to reset
- set_font(font_dict=None)¶
Set the font and font properties.
- Parameters:
font_dict (dict) –
A dict of keyword parameters to be passed to
matplotlib.font_manager.FontProperties
.Possible keys include:
family - The font family. Can be serif, sans-serif, cursive, ‘fantasy’ or ‘monospace’.
style - The font style. Either normal, italic or oblique.
color - A valid color string like ‘r’, ‘g’, ‘red’, ‘cobalt’, and ‘orange’.
variant - Either normal or small-caps.
size - Either a relative value of xx-small, x-small, small, medium, large, x-large, xx-large or an absolute font size, e.g. 12
stretch - A numeric value in the range 0-1000 or one of ultra-condensed, extra-condensed, condensed, semi-condensed, normal, semi-expanded, expanded, extra-expanded or ultra-expanded
weight - A numeric value in the range 0-1000 or one of ultralight, light, normal, regular, book, medium, roman, semibold, demibold, demi, bold, heavy, extra bold, or black
See the matplotlib font manager API documentation for more details. https://matplotlib.org/stable/api/font_manager_api.html
Notes
Mathtext axis labels will only obey the size and color keyword.
Examples
This sets the font to be 24-pt, blue, sans-serif, italic, and bold-face.
>>> slc = SlicePlot(ds, "x", "Density") >>> slc.set_font( ... { ... "family": "sans-serif", ... "style": "italic", ... "weight": "bold", ... "size": 24, ... "color": "blue", ... } ... )
- set_font_size(size)¶
Set the size of the font used in the plot
This sets the font size by calling the set_font function. See set_font for more font customization options.
- Parameters:
size (float)
inch). (The absolute size of the font in points (1 pt = 1/72)
- set_log(field, log: bool | None = None, *, linthresh: float | unyt_quantity | tuple[float, Unit | str] | Literal['auto'] | None = None, symlog_auto: bool | None = None)¶
set a field to log, linear, or symlog.
Symlog scaling is a combination of linear and log, where from 0 to a threshold value, it operates as linear, and then beyond that it operates as log. Symlog can also work with negative values in log space as well as negative and positive values simultaneously and symmetrically. If symlog scaling is desired, please set log=True and either set symlog_auto=True or select a value for linthresh.
- Parameters:
field (string) – the field to set a transform if field == ‘all’, applies to all plots.
log (boolean, optional) – set log to True for log scaling, False for linear scaling.
linthresh (float, (float, str), unyt_quantity, or 'auto', optional) – when using symlog scaling, linthresh is the value at which scaling transitions from linear to logarithmic. linthresh must be positive. Note: setting linthresh will automatically enable symlog scale
arguments (Note that log and linthresh are mutually exclusive)
- set_minorticks(field, state)¶
Turn minor ticks on or off in the current plot.
Displaying minor ticks reduces performance; turn them off using set_minorticks(‘all’, False) if drawing speed is a problem.
- Parameters:
field (string) – the field to remove minorticks if field == ‘all’, applies to all plots.
state (bool) – the state indicating ‘on’ (True) or ‘off’ (False)
- set_mpl_projection(mpl_proj)¶
Set the matplotlib projection type with a cartopy transform function
Given a string or a tuple argument, this will project the data onto the plot axes with the chosen transform function.
Assumes that the underlying data has a PlateCarree transform type.
To annotate the plot with coastlines or other annotations, render() will need to be called after this function to make the axes available for annotation.
- Parameters:
mpl_proj (string or tuple) – if passed as a string, mpl_proj is the specified projection type, if passed as a tuple, then tuple will take the form of
("ProjectionType", (args))
or("ProjectionType", (args), {kwargs})
Valid projection type options include: ‘PlateCarree’, ‘LambertConformal’, ‘LabmbertCylindrical’, ‘Mercator’, ‘Miller’, ‘Mollweide’, ‘Orthographic’, ‘Robinson’, ‘Stereographic’, ‘TransverseMercator’, ‘InterruptedGoodeHomolosine’, ‘RotatedPole’, ‘OGSB’, ‘EuroPP’, ‘Geostationary’, ‘Gnomonic’, ‘NorthPolarStereo’, ‘OSNI’, ‘SouthPolarStereo’, ‘AlbersEqualArea’, ‘AzimuthalEquidistant’, ‘Sinusoidal’, ‘UTM’, ‘NearsidePerspective’, ‘LambertAzimuthalEqualArea’
Examples
This will create a Mollweide projection using Mollweide default values and annotate it with coastlines
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection("AIRDENS", "Mollweide") >>> p.render() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will move the PlateCarree central longitude to 90 degrees and annotate with coastlines.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection( ... "AIRDENS", ("PlateCarree", (), {"central_longitude": 90, "globe": None}) ... ) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will create a RoatatedPole projection with the unrotated pole position at 37.5 degrees latitude and 177.5 degrees longitude by passing them in as args.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection("RotatedPole", (177.5, 37.5)) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will create a RoatatedPole projection with the unrotated pole position at 37.5 degrees latitude and 177.5 degrees longitude by passing them in as kwargs.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection( ... ("RotatedPole", (), {"pole_latitude": 37.5, "pole_longitude": 177.5}) ... ) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
- set_norm(field, norm: Normalize)¶
Set a custom
matplotlib.colors.Normalize
to plot field.Any constraints previously set with set_log, set_zlim will be dropped.
Note that any float value attached to norm (e.g. vmin, vmax, vcenter …) will be read in the current displayed units, which can be controlled with the set_unit method.
- Parameters:
field (str or tuple[str, str]) – if field == ‘all’, applies to all plots.
norm (matplotlib.colors.Normalize) – see https://matplotlib.org/stable/tutorials/colors/colormapnorms.html
- set_origin(origin)¶
Set the plot origin.
- Parameters:
origin (string or length 1, 2, or 3 sequence.) – The location of the origin of the plot coordinate system. This is typically represented by a ‘-’ separated string or a tuple of strings. In the first index the y-location is given by ‘lower’, ‘upper’, or ‘center’. The second index is the x-location, given as ‘left’, ‘right’, or ‘center’. Finally, whether the origin is applied in ‘domain’ space, plot ‘window’ space or ‘native’ simulation coordinate system is given. For example, both ‘upper-right-domain’ and [‘upper’, ‘right’, ‘domain’] place the origin in the upper right hand corner of domain space. If x or y are not given, a value is inferred. For instance, ‘left-domain’ corresponds to the lower-left hand corner of the simulation domain, ‘center-domain’ corresponds to the center of the simulation domain, or ‘center-window’ for the center of the plot window. In the event that none of these options place the origin in a desired location, a sequence of tuples and a string specifying the coordinate space can be given. If plain numeric types are input, units of code_length are assumed. Further examples:
=============================== (===============================================)
example (format)
===============================
'domain' ('{space}')
'left-window' ('{xloc}-{space}')
'upper-domain' ('{yloc}-{space}')
'lower-right-window' ('{yloc}-{xloc}-{space}')
('{space}'
('window' ())
)
('{xloc}'
('right' ('{space}'))
'domain')
('{yloc}'
('lower' ('{space}'))
'window')
('{yloc}'
'{xloc}'
('lower'
'right'
'window')
((yloc
'{unit}')
(xloc
'{unit}')
((0 ('{space}'))
'm')
(.4
'm')
'window')
(xloc
yloc
(0.23 ('{space}'))
0.5
'domain')
===============================
- set_unit(field, new_unit, equivalency=None, equivalency_kwargs=None)¶
Sets a new unit for the requested field
- Parameters:
field (string or field tuple) – The name of the field that is to be changed.
new_unit (string or Unit object)
equivalency (string, optional) – If set, the equivalency to use to convert the current units to the new requested unit. If None, the unit conversion will be done without an equivalency
equivalency_kwargs (string, optional) – Keyword arguments to be passed to the equivalency. Only used if
equivalency
is set.
- set_width(width, unit=None)¶
set the width of the plot window
- Parameters:
width (float, array of floats, (float, unit) tuple, or tuple of) –
(float, unit) tuples.
Width can have four different formats to support windows with variable x and y widths. They are:
format
example
(float, string)
(10,’kpc’)
((float, string), (float, string))
((10,’kpc’),(15,’kpc’))
float
0.2
(float, float)
(0.2, 0.3)
For example, (10, ‘kpc’) requests a plot window that is 10 kiloparsecs wide in the x and y directions, ((10,’kpc’),(15,’kpc’)) requests a window that is 10 kiloparsecs wide along the x axis and 15 kiloparsecs wide along the y axis. In the other two examples, code units are assumed, for example (0.2, 0.3) requests a plot that has an x width of 0.2 and a y width of 0.3 in code units. If units are provided the resulting plot axis labels will use the supplied units.
unit (str) – the unit the width has been specified in. If width is a tuple, this argument is ignored. Defaults to code units.
- set_xlabel(label)¶
Allow the user to modify the X-axis title Defaults to the global value. Fontsize defaults to 18.
- Parameters:
label (str) – The new string for the x-axis.
(cm$^{-3}$)") (>>> plot.set_xlabel("H2I Number Density)
- set_ylabel(label)¶
Allow the user to modify the Y-axis title Defaults to the global value.
- Parameters:
label (str) – The new string for the y-axis.
(K)") (>>> plot.set_ylabel("Temperature)
- set_zlim(field, zmin: ~unyt.array.unyt_quantity | tuple[float, ~unyt.unit_object.Unit | str] | float | ~typing.Literal['min'] | ~yt.visualization.plot_container.Unset = <yt.visualization.plot_container.Unset object>, zmax: ~unyt.array.unyt_quantity | tuple[float, ~unyt.unit_object.Unit | str] | float | ~typing.Literal['max'] | ~yt.visualization.plot_container.Unset = <yt.visualization.plot_container.Unset object>, dynamic_range: float | None = None)¶
set the scale of the colormap
- Parameters:
field (string) – the field to set a colormap scale if field == ‘all’, applies to all plots.
zmin (float, Quantity, or 'min') – the new minimum of the colormap scale. If ‘min’, will set to the minimum value in the current view.
zmax (float, Quantity, or 'max') – the new maximum of the colormap scale. If ‘max’, will set to the maximum value in the current view.
dynamic_range (float (default: None)) – The dynamic range of the image. If zmin == None, will set zmin = zmax / dynamic_range If zmax == None, will set zmax = zmin * dynamic_range
- setup_callbacks()¶
- show()¶
This will send any existing plots to the IPython notebook.
If yt is being run from within an IPython session, and it is able to determine this, this function will send any existing plots to the notebook for display.
If yt can’t determine if it’s inside an IPython session, it will raise YTNotInsideNotebook.
Examples
>>> from yt import SlicePlot >>> slc = SlicePlot( ... ds, "x", [("gas", "density"), ("gas", "velocity_magnitude")] ... ) >>> slc.show()
- show_axes(field=None)¶
Shows the axes for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object. See hide_axes().
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to show the axes.
- show_colorbar(field=None)¶
Shows the colorbar for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object. See hide_colorbar().
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional))
colorbar. (The name of the field(s) that we want to show the)
- swap_axes()¶
- to_fits_data(fields=None, other_keys=None, length_unit=None, **kwargs)¶
Export the fields in this PlotWindow instance to a FITSImageData instance.
This will export a set of FITS images of either the fields specified or all the fields already in the object.
- Parameters:
fields (list of strings) – These fields will be pixelized and output. If “None”, the keys of the FRB will be used.
other_keys (dictionary, optional) – A set of header keys and values to write into the FITS header.
length_unit (string, optional) – the length units that the coordinates are written in. The default is to use the default length unit of the dataset.
- property width¶
- class yt.visualization.plot_window.PWViewerMPL(*args, **kwargs)[source]¶
Bases:
PlotWindow
Viewer using matplotlib as a backend via the WindowPlotMPL.
- annotate_arrow(pos, *, length=0.03, width=0.0001, head_width=0.01, head_length=0.01, starting_pos=None, coord_system='data', plot_args: dict[str, Any] | None = None, **kwargs)¶
Overplot arrow(s) pointing at position(s) for highlighting specific features. By default, arrow points from lower left to the designated position “pos” with arrow length “length”. Alternatively, if “starting_pos” is set, arrow will stretch from “starting_pos” to “pos” and “length” will be disregarded.
“coord_system” keyword refers to positions set in “pos” arg and “starting_pos” keyword, which by default are in data coordinates.
“length”, “width”, “head_length”, and “head_width” keywords for the arrow are all in axis units, ie relative to the size of the plot axes as 1, even if the position of the arrow is set relative to another coordinate system.
- Parameters:
pos (array-like) – These are the coordinates where the marker(s) will be overplotted Either as [x,y,z] or as [[x1,x2,…],[y1,y2,…],[z1,z2,…]]
length (float, optional) – The length, in axis units, of the arrow. Default: 0.03
width (float, optional) – The width, in axis units, of the tail line of the arrow. Default: 0.003
head_length (float, optional) – The length, in axis units, of the head of the arrow. If set to None, use 1.5*head_width Default: None
head_width (float, optional) – The width, in axis units, of the head of the arrow. Default: 0.02
starting_pos (2- or 3-element tuple, list, or array, optional) – These are the coordinates from which the arrow starts towards its point. Not compatible with ‘length’ kwarg.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
plot_args (dictionary, optional) – This dictionary is passed to the MPL arrow function for generating the arrow. By default, it is: {‘color’:’white’}
Examples
>>> # Overplot an arrow pointing to feature at data coord: (0.2, 0.3, 0.4) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_arrow([0.2, 0.3, 0.4]) >>> s.save()
>>> # Overplot a red arrow with longer length pointing to plot coordinate >>> # (0.1, -0.1) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_arrow( ... [0.1, -0.1], length=0.06, coord_system="plot", color="red" ... ) >>> s.save()
- annotate_cell_edges(line_width=0.002, alpha=1.0, color='black')¶
Annotate cell edges. This is done through a second call to pixelize, where the distance from a pixel to a cell boundary in pixels is compared against the line_width argument. The secondary image is colored as color and overlaid with the alpha value.
- Parameters:
line_width (float) – The width of the cell edge lines in normalized units relative to the size of the longest axis. Default is 1% of the size of the smallest axis.
alpha (float) – When the second image is overlaid, it will have this level of alpha transparency. Default is 1.0 (fully-opaque).
color (tuple of three floats or matplotlib color name) – This is the color of the cell edge values. It defaults to black.
Examples
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_cell_edges() >>> s.save()
- annotate_clumps(clumps, *, plot_args=None, **kwargs)¶
Take a list of clumps and plot them as a set of contours.
- annotate_contour(field: tuple[str, str] | str, levels: int = 5, *, factor: tuple[int, int] | int = 4, clim: tuple[float, float] | None = None, label: bool = False, take_log: bool | None = None, data_source: YTDataContainer | None = None, plot_args: dict[str, Any] | None = None, text_args: dict[str, Any] | None = None, ncont: int | None = None) None ¶
Add contours in field to the plot. levels governs the number of contours generated, factor governs the number of points used in the interpolation, take_log governs how it is contoured and clim gives the (lower, upper) limits for contouring. An alternate data source can be specified with data_source, but by default the plot’s data source will be queried.
- annotate_cquiver(field_x, field_y, field_c=None, *, factor: tuple[int, int] | int = 16, scale=None, scale_units=None, normalize=False, plot_args=None, **kwargs)¶
Get a quiver plot on top of a cutting plane, using field_x and field_y, skipping every factor datapoint in the discretization. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- annotate_grids(alpha=0.7, min_pix=1, min_pix_ids=20, draw_ids=False, id_loc=None, periodic=True, min_level=None, max_level=None, cmap='B-W LINEAR_r', edgecolors=None, linewidth=1.0)¶
Draws grids on an existing PlotWindow object. Adds grid boundaries to a plot, optionally with alpha-blending. By default, colors different levels of grids with different colors going from white to black, but you can change to any arbitrary colormap with cmap keyword, to all black grid edges for all levels with cmap=None and edgecolors=None, or to an arbitrary single color for grid edges with edgecolors=’YourChosenColor’ defined in any of the standard ways (e.g., edgecolors=’white’, edgecolors=’r’, edgecolors=’#00FFFF’, or edgecolor=’0.3’, where the last is a float in 0-1 scale indicating gray). Note that setting edgecolors overrides cmap if you have both set to non-None values. Cutoff for display is at min_pix wide. draw_ids puts the grid id a the corner of the grid (but its not so great in projections…). id_loc determines which corner holds the grid id. One can set min and maximum level of grids to display, and can change the linewidth of the displayed grids.
- annotate_line(p1, p2, *, coord_system='data', plot_args: dict[str, Any] | None = None, **kwargs)¶
Overplot a line with endpoints at p1 and p2. p1 and p2 should be 2D or 3D coordinates consistent with the coordinate system denoted in the “coord_system” keyword.
- Parameters:
p1 (2- or 3-element tuples, lists, or arrays) – These are the coordinates of the endpoints of the line.
p2 (2- or 3-element tuples, lists, or arrays) – These are the coordinates of the endpoints of the line.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates p1 and p2. Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
plot_args (dictionary, optional) – This dictionary is passed to the MPL plot function for generating the line. By default, it is: {‘color’:’white’, ‘linewidth’:2}
Examples
>>> # Overplot a diagonal white line from the lower left corner to upper >>> # right corner >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_line([0, 0], [1, 1], coord_system="axis") >>> s.save()
>>> # Overplot a red dashed line from data coordinate (0.1, 0.2, 0.3) to >>> # (0.5, 0.6, 0.7) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_line( ... [0.1, 0.2, 0.3], ... [0.5, 0.6, 0.7], ... coord_system="data", ... color="red", ... linestyles="--", ... ) >>> s.save()
- annotate_line_integral_convolution(field_x, field_y, texture=None, kernellen=50.0, lim=(0.5, 0.6), cmap='binary', alpha=0.8, const_alpha=False)¶
Add the line integral convolution to the plot for vector fields visualization. Two component of vector fields needed to be provided (i.e., velocity_x and velocity_y, magnetic_field_x and magnetic_field_y).
- Parameters:
field_x (string) – The names of two components of vector field which will be visualized
field_y (string) – The names of two components of vector field which will be visualized
texture (2-d array with the same shape of image, optional) – Texture will be convolved when computing line integral convolution. A white noise background will be used as default.
kernellen (float, optional) – The lens of kernel for convolution, which is the length over which the convolution will be performed. For longer kernellen, longer streamline structure will appear.
lim (2-element tuple, list, or array, optional) – The value of line integral convolution will be clipped to the range of lim, which applies upper and lower bounds to the values of line integral convolution and enhance the visibility of plots. Each element should be in the range of [0,1].
cmap (string, optional) – The name of colormap for line integral convolution plot.
alpha (float, optional) – The alpha value for line integral convolution plot.
const_alpha (boolean, optional) – If set to False (by default), alpha will be weighted spatially by the values of line integral convolution; otherwise a constant value of the given alpha is used.
Example
>>> import yt >>> ds = yt.load("Enzo_64/DD0020/data0020") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_line_integral_convolution( ... "velocity_x", "velocity_y", lim=(0.5, 0.65) ... )
- annotate_magnetic_field(factor: tuple[int, int] | int = 16, *, scale=None, scale_units=None, normalize=False, plot_args=None, **kwargs)¶
Adds a ‘quiver’ plot of magnetic field to the plot, skipping all but every factor datapoint. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the magnetic fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- annotate_marker(pos, marker='x', *, coord_system='data', plot_args=None, **kwargs)¶
Overplot marker(s) at a position(s) for highlighting specific features.
- Parameters:
pos (array-like) – These are the coordinates where the marker(s) will be overplotted Either as [x,y,z] or as [[x1,x2,…],[y1,y2,…],[z1,z2,…]]
marker (string, optional) – The shape of the marker to be passed to the MPL scatter function. By default, it is ‘x’, but other acceptable values are: ‘.’, ‘o’, ‘v’, ‘^’, ‘s’, ‘p’ ‘*’, etc. See matplotlib.markers for more information.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
plot_args (dictionary, optional) – This dictionary is passed to the MPL scatter function for generating the marker. By default, it is: {‘color’:’white’, ‘s’:50}
Examples
>>> # Overplot a white X on a feature at data location (0.5, 0.5, 0.5) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_marker([0.4, 0.5, 0.6]) >>> s.save()
>>> # Overplot a big yellow circle at axis location (0.1, 0.2) >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_marker( ... [0.1, 0.2], ... marker="o", ... coord_system="axis", ... color="yellow", ... s=200, ... ) >>> s.save()
- annotate_mesh_lines(*, plot_args=None, **kwargs)¶
Adds mesh lines to the plot. Only works for unstructured or semi-structured mesh data. For structured grid data, see GridBoundaryCallback or CellEdgesCallback.
- Parameters:
plot_args (dict, optional) – A dictionary of arguments that will be passed to matplotlib.
Example
>>> import yt >>> ds = yt.load("MOOSE_sample_data/out.e-s010") >>> sl = yt.SlicePlot(ds, "z", ("connect2", "convected")) >>> sl.annotate_mesh_lines(color="black")
- annotate_particles(width, p_size=1.0, col='k', marker='o', stride=1, ptype='all', alpha=1.0, data_source=None)¶
Adds particle positions, based on a thick slab along axis with a width along the line of sight. p_size controls the number of pixels per particle, and col governs the color. ptype will restrict plotted particles to only those that are of a given type. alpha determines the opacity of the marker symbol used in the scatter. An alternate data source can be specified with data_source, but by default the plot’s data source will be queried.
- annotate_quiver(field_x, field_y, field_c=None, *, factor: tuple[int, int] | int = 16, scale=None, scale_units=None, normalize=False, bv_x=0, bv_y=0, plot_args=None, **kwargs)¶
Adds a ‘quiver’ plot to any plot, using the field_x and field_y from the associated data, skipping every factor pixels. field_c is an optional field name used for color. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- annotate_ray(ray, *, arrow=False, plot_args=None, **kwargs)¶
Adds a line representing the projected path of a ray across the plot. The ray can be either a YTOrthoRay, YTRay, or a LightRay object. annotate_ray() will properly account for periodic rays across the volume. If arrow is set to True, uses the MPL.pyplot.arrow function, otherwise uses the MPL.pyplot.plot function to plot a normal line. Adjust plot_args accordingly.
- Parameters:
ray (YTOrthoRay, YTRay, or LightRay) – Ray is the object that we want to include. We overplot the projected trajectory of the ray. If the object is a trident.LightRay object, it will only plot the segment of the LightRay that intersects the dataset currently displayed.
arrow (boolean, optional) – Whether or not to place an arrowhead on the front of the ray to denote direction Default: False
plot_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib line object. Defaults: {‘color’:’white’, ‘linewidth’:2}.
Examples
>>> # Overplot a ray and an ortho_ray object on a projection >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> oray = ds.ortho_ray(1, (0.3, 0.4)) # orthoray down the y axis >>> ray = ds.ray((0.1, 0.2, 0.3), (0.6, 0.7, 0.8)) # arbitrary ray >>> p = yt.ProjectionPlot(ds, "z", "density") >>> p.annotate_ray(oray) >>> p.annotate_ray(ray) >>> p.save()
>>> # Overplot a LightRay object on a projection >>> import yt >>> from trident import LightRay >>> ds = yt.load("enzo_cosmology_plus/RD0004/RD0004") >>> lr = LightRay( ... "enzo_cosmology_plus/AMRCosmology.enzo", "Enzo", 0.0, 0.1, time_data=False ... ) >>> lray = lr.make_light_ray(seed=1) >>> p = yt.ProjectionPlot(ds, "z", "density") >>> p.annotate_ray(lr) >>> p.save()
- annotate_scale(*, corner='lower_right', coeff=None, unit=None, pos=None, max_frac=0.16, min_frac=0.015, coord_system='axis', text_args=None, size_bar_args=None, draw_inset_box=False, inset_box_args=None, scale_text_format='{scale} {units}')¶
Annotates the scale of the plot at a specified location in the image (either in a preset corner, or by specifying (x,y) image coordinates with the pos argument. Coeff and units (e.g. 1 Mpc or 100 kpc) refer to the distance scale you desire to show on the plot. If no coeff and units are specified, an appropriate pair will be determined such that your scale bar is never smaller than min_frac or greater than max_frac of your plottable axis length. Additional customization of the scale bar is possible by adjusting the text_args and size_bar_args dictionaries. The text_args dictionary accepts matplotlib’s font_properties arguments to override the default font_properties for the current plot. The size_bar_args dictionary accepts keyword arguments for the AnchoredSizeBar class in matplotlib’s axes_grid toolkit.
- Parameters:
corner (string, optional) – Corner sets up one of 4 predeterimined locations for the scale bar to be displayed in the image: ‘upper_left’, ‘upper_right’, ‘lower_left’, ‘lower_right’ (also allows None). This value will be overridden by the optional ‘pos’ keyword.
coeff (float, optional) – The coefficient of the unit defining the distance scale (e.g. 10 kpc or 100 Mpc) for overplotting. If set to None along with unit keyword, coeff will be automatically determined to be a power of 10 relative to the best-fit unit.
unit (string, optional) – unit must be a valid yt distance unit (e.g. ‘m’, ‘km’, ‘AU’, ‘pc’, ‘kpc’, etc.) or set to None. If set to None, will be automatically determined to be the best-fit to the data.
pos (2- or 3-element tuples, lists, or arrays, optional) – The image location of the scale bar in the plot coordinate system. Setting pos overrides the corner parameter.
min_frac (float, optional) – The minimum/maximum fraction of the axis width for the scale bar to extend. A value of 1 would allow the scale bar to extend across the entire axis width. Only used for automatically calculating best-fit coeff and unit when neither is specified, otherwise disregarded.
max_frac (float, optional) – The minimum/maximum fraction of the axis width for the scale bar to extend. A value of 1 would allow the scale bar to extend across the entire axis width. Only used for automatically calculating best-fit coeff and unit when neither is specified, otherwise disregarded.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data”: 3D dataset coordinates
”plot”: 2D coordinates defined by the actual plot limits
”axis”: MPL axis coordinates: (0,0) is lower left; (1,1) is upper right
”figure”: MPL figure coordinates: (0,0) is lower left, (1,1) is upper right
text_args (dictionary, optional) – A dictionary of parameters to used to update the font_properties for the text in this callback. For any property not set, it will use the defaults of the plot. Thus one can modify the text size with
text_args={'size':24}
size_bar_args (dictionary, optional) – A dictionary of parameters to be passed to the Matplotlib AnchoredSizeBar initializer. Defaults:
{'pad': 0.25, 'sep': 5, 'borderpad': 1, 'color': 'w'}
draw_inset_box (boolean, optional) – Whether or not an inset box should be included around the scale bar.
inset_box_args (dictionary, optional) – A dictionary of keyword arguments to be passed to the matplotlib Patch object that represents the inset box. Defaults:
{'facecolor': 'black', 'linewidth': 3, 'edgecolor': 'white', 'alpha': 0.5, 'boxstyle': 'square'}
scale_text_format (string, optional) – This specifies the format of the scalebar value assuming “scale” is the numerical value and “unit” is units of the scale (e.g. ‘cm’, ‘kpc’, etc.) The scale can be specified to arbitrary precision according to printf formatting codes. The format string must only specify “scale” and “units”. Example: “Length = {scale:.2f} {units}”. Default: “{scale} {units}”
Example
>>> import yt >>> ds = yt.load("Enzo_64/DD0020/data0020") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_scale()
- annotate_sphere(center, radius, *, coord_system='data', text=None, circle_args=None, text_args=None)¶
Overplot a circle with designated center and radius with optional text.
- Parameters:
center (2- or 3-element tuple, list, or array) – These are the coordinates where the circle will be overplotted
radius (YTArray, float, or (1, ('kpc')) style tuple) – The radius of the circle in code coordinates
circle_args (dict, optional) – This dictionary is passed to the MPL circle object. By default, {‘color’:’white’}
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
text (string, optional) – Optional text to include next to the circle.
text_args (dictionary, optional) – This dictionary is passed to the MPL text function. By default, it is: {‘color’:’white’}
Examples
>>> # Overplot a white circle of radius 100 kpc over the central galaxy >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_sphere([0.5, 0.5, 0.5], radius=(100, "kpc")) >>> s.save()
- annotate_streamlines(field_x: tuple[str, str] | str, field_y: tuple[str, str] | str, *, linewidth: float | tuple[str, str] | str = 1.0, linewidth_upscaling: float = 1.0, color: Any | tuple[str, str] | None = None, color_threshold: float | unyt_quantity = -inf, factor: tuple[int, int] | int = 16, field_color=None, display_threshold=None, plot_args=None, **kwargs)¶
Plot streamlines using matplotlib.axes.Axes.streamplot
- Parameters:
field_x (field key) – The “velocity” analoguous field along the horizontal direction.
field_y (field key) – The “velocity” analoguous field along the vertical direction.
linewidth (float, or field key (default: 1.0)) – A constant scalar will be passed directly to matplotlib.axes.Axes.streamplot A field key will be first interpreted by yt and produce the adequate 2D array. Data fields are normalized by their maximum value, so the maximal linewidth is 1 by default. See linewidth_upscaling for fine tuning. Note that the absolute value is taken in all cases.
linewidth_upscaling (float (default: 1.0)) – A constant multiplicative factor applied to linewidth. Final linewidth is obtained as: linewidth_upscaling * abs(linewidth) / max(abs(linewidth))
color (a color identifier, or a field key (default: matplotlib.rcParams['line.color'])) – A constant color identifier will be passed directly to matplotlib.axes.Axes.streamplot A field key will be first interpreted by yt and produce the adequate 2D array. See https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.streamplot.html for how to customize color mapping using cmap and norm arguments.
color_threshold (float or unyt_quantity (default: -inf)) – Regions where the field used for color is lower than this threshold will be masked. Only used if color is a field key.
factor (int, or tuple[int, int] (default: 16)) – Fields are downed-sampled by this factor with respect to the background image buffer size. A single integer factor will be used for both direction, but a tuple of 2 integers can be passed to set x and y downsampling independently.
**kwargs (any additional keyword arguments will be passed) – directly to matplotlib.axes.Axes.streamplot
- annotate_text(pos, text, *, coord_system='data', text_args=None, inset_box_args=None)¶
Overplot text on the plot at a specified position. If you desire an inset box around your text, set one with the inset_box_args dictionary keyword.
- Parameters:
pos (2- or 3-element tuple, list, or array) – These are the coordinates where the text will be overplotted
text (string) – The text you wish to include
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data” – the 3D dataset coordinates
”plot” – the 2D coordinates defined by the actual plot limits
- ”axis” – the MPL axis coordinates: (0,0) is lower left; (1,1) is
upper right
- ”figure” – the MPL figure coordinates: (0,0) is lower left, (1,1)
is upper right
text_args (dictionary, optional) – This dictionary is passed to the MPL text function for generating the text. By default, it is: {‘color’:’white’} and uses the defaults for the other fonts in the image.
inset_box_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib FancyBboxPatch object as the inset box around the text. Default: {}
Examples
>>> # Overplot white text at data location [0.55, 0.7, 0.4] >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_text([0.55, 0.7, 0.4], "Here is a galaxy") >>> s.save()
>>> # Overplot yellow text at axis location [0.2, 0.8] with >>> # a shaded inset box >>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_text( ... [0.2, 0.8], ... "Here is a galaxy", ... coord_system="axis", ... text_args={"color": "yellow"}, ... inset_box_args={ ... "boxstyle": "square,pad=0.3", ... "facecolor": "black", ... "linewidth": 3, ... "edgecolor": "white", ... "alpha": 0.5, ... }, ... ) >>> s.save()
- annotate_timestamp(x_pos=None, y_pos=None, corner='lower_left', *, time=True, redshift=False, time_format='t = {time:.1f} {units}', time_unit=None, redshift_format='z = {redshift:.2f}', draw_inset_box=False, coord_system='axis', time_offset=None, text_args=None, inset_box_args=None)¶
Annotates the timestamp and/or redshift of the data output at a specified location in the image (either in a present corner, or by specifying (x,y) image coordinates with the x_pos, y_pos arguments. If no time_units are specified, it will automatically choose appropriate units. It allows for custom formatting of the time and redshift information, as well as the specification of an inset box around the text.
- Parameters:
x_pos (floats, optional) – The image location of the timestamp in the coord system defined by the coord_system kwarg. Setting x_pos and y_pos overrides the corner parameter.
y_pos (floats, optional) – The image location of the timestamp in the coord system defined by the coord_system kwarg. Setting x_pos and y_pos overrides the corner parameter.
corner (string, optional) – Corner sets up one of 4 predeterimined locations for the timestamp to be displayed in the image: ‘upper_left’, ‘upper_right’, ‘lower_left’, ‘lower_right’ (also allows None). This value will be overridden by the optional x_pos and y_pos keywords.
time (boolean, optional) – Whether or not to show the ds.current_time of the data output. Can be used solo or in conjunction with redshift parameter.
redshift (boolean, optional) – Whether or not to show the ds.current_time of the data output. Can be used solo or in conjunction with the time parameter.
time_format (string, optional) – This specifies the format of the time output assuming “time” is the number of time and “unit” is units of the time (e.g. ‘s’, ‘Myr’, etc.) The time can be specified to arbitrary precision according to printf formatting codes (defaults to .1f – a float with 1 digits after decimal). Example: “Age = {time:.2f} {units}”.
time_unit (string, optional) – time_unit must be a valid yt time unit (e.g. ‘s’, ‘min’, ‘hr’, ‘yr’, ‘Myr’, etc.)
redshift_format (string, optional) – This specifies the format of the redshift output. The redshift can be specified to arbitrary precision according to printf formatting codes (defaults to 0.2f – a float with 2 digits after decimal). Example: “REDSHIFT = {redshift:03.3g}”,
draw_inset_box (boolean, optional) – Whether or not an inset box should be included around the text If so, it uses the inset_box_args to set the matplotlib FancyBboxPatch object.
coord_system (string, optional) –
This string defines the coordinate system of the coordinates of pos Valid coordinates are:
”data”: 3D dataset coordinates
”plot”: 2D coordinates defined by the actual plot limits
”axis”: MPL axis coordinates: (0,0) is lower left; (1,1) is upper right
”figure”: MPL figure coordinates: (0,0) is lower left, (1,1) is upper right
time_offset (float, (value, unit) tuple, or YTQuantity, optional) – Apply an offset to the time shown in the annotation from the value of the current time. If a scalar value with no units is passed in, the value of the time_unit kwarg is used for the units. Default: None, meaning no offset.
text_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib text object. Defaults:
{'color':'white', 'horizontalalignment':'center', 'verticalalignment':'top'}
.inset_box_args (dictionary, optional) – A dictionary of any arbitrary parameters to be passed to the Matplotlib FancyBboxPatch object as the inset box around the text. Defaults:
{'boxstyle':'square', 'pad':0.3, 'facecolor':'black', 'linewidth':3, 'edgecolor':'white', 'alpha':0.5}
Example
>>> import yt >>> ds = yt.load("Enzo_64/DD0020/data0020") >>> s = yt.SlicePlot(ds, "z", "density") >>> s.annotate_timestamp()
- annotate_title(title)¶
Accepts a title and adds it to the plot
- annotate_triangle_facets(triangle_vertices, *, plot_args=None, **kwargs)¶
Intended for representing a slice of a triangular faceted geometry in a slice plot.
Uses a set of triangle_vertices to find all triangles the plane of a SlicePlot intersects with. The lines between the intersection points of the triangles are then added to the plot to create an outline of the geometry represented by the triangles.
- annotate_velocity(factor: tuple[int, int] | int = 16, *, scale=None, scale_units=None, normalize=False, plot_args=None, **kwargs)¶
Adds a ‘quiver’ plot of velocity to the plot, skipping all but every factor datapoint. scale is the data units per arrow length unit using scale_units and plot_args allows you to pass in matplotlib arguments (see matplotlib.axes.Axes.quiver for more info). if normalize is True, the velocity fields will be scaled by their local (in-plane) length, allowing morphological features to be more clearly seen for fields with substantial variation in field strength.
- property bounds¶
- clear_annotations(index: int | None = None)[source]¶
Clear callbacks from the plot. If index is not set, clear all callbacks. If index is set, clear that index (ie 0 is the first one created, 1 is the 2nd one created, -1 is the last one created, etc.)
- display(name=None, mpl_kwargs=None)¶
Will attempt to show the plot in in an IPython notebook. Failing that, the plot will be saved to disk.
- export_to_mpl_figure(nrows_ncols, axes_pad=1.0, label_mode='L', cbar_location='right', cbar_size='5%', cbar_mode='each', cbar_pad='0%')[source]¶
Creates a matplotlib figure object with the specified axes arrangement, nrows_ncols, and maps the underlying figures to the matplotlib axes. Note that all of these parameters are fed directly to the matplotlib ImageGrid class to create the new figure layout.
- Parameters:
nrows_ncols (tuple) – the number of rows and columns of the axis grid (e.g., nrows_ncols=(2,2,))
axes_pad (float) – padding between axes in inches
label_mode (one of "L", "1", "all") – arrangement of axes that are labeled
cbar_location (one of "left", "right", "bottom", "top") – where to place the colorbar
cbar_size (string (percentage)) – scaling of the colorbar (e.g., “5%”)
cbar_mode (one of "each", "single", "edge", None) – how to represent the colorbar
cbar_pad (string (percentage)) – padding between the axis and colorbar (e.g. “5%”)
- Return type:
The return is a matplotlib figure object.
Examples
>>> import yt >>> ds = yt.load_sample("IsolatedGalaxy") >>> fields = ["density", "velocity_x", "velocity_y", "velocity_magnitude"] >>> p = yt.SlicePlot(ds, "z", fields) >>> p.set_log("velocity_x", False) >>> p.set_log("velocity_y", False) >>> fig = p.export_to_mpl_figure((2, 2)) >>> fig.tight_layout() >>> fig.savefig("test.png")
- flip_horizontal()¶
inverts the horizontal axis (the image’s abscissa)
- flip_vertical()¶
inverts the vertical axis (the image’s ordinate)
- property frb¶
- get_log(field)¶
get the transform type of a field.
- Parameters:
field (string) – the field to get a transform if field == ‘all’, applies to all plots.
- hide_axes(field=None, draw_frame=None)¶
Hides the axes for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object.
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to hide the axes.
draw_frame (boolean) – If True, the axes frame will still be drawn. Defaults to False. See note below for more details.
Examples
This will save an image with no axes.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.save()
This will save an image with no axis or colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.hide_colorbar() >>> s.save()
Note
By default, when removing the axes, the patch on which the axes are drawn is disabled, making it impossible to later change e.g. the background colour. To force the axes patch to be displayed while still hiding the axes, set the
draw_frame
keyword argument toTrue
.
- hide_colorbar(field=None)¶
Hides the colorbar for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object.
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to hide the colorbar. If None or ‘all’ is provided, will default to using all fields available for this object.
Examples
This will save an image with no colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_colorbar() >>> s.save()
This will save an image with no axis or colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.hide_colorbar() >>> s.save()
- list_annotations()[source]¶
List the current callbacks for the plot, along with their index. This index can be used with clear_annotations to remove a callback from the current plot.
- pan(deltas)¶
Pan the image by specifying absolute code unit coordinate deltas.
- Parameters:
deltas (Two-element sequence of floats, quantities, or (float, unit)) –
tuples.
(delta_x, delta_y). If a unit is not supplied the unit is assumed to be code_length.
- pan_rel(deltas)¶
Pan the image by specifying relative deltas, to the FOV.
- Parameters:
deltas (sequence of floats) – (delta_x, delta_y) in relative code unit coordinates
- piter(*args, **kwargs)¶
- refresh()¶
- render() None ¶
Render plots. This operation is expensive and usually doesn’t need to be requested explicitly. In most cases, yt handles rendering automatically and delays it as much as possible to avoid redundant calls on each plot modification (e.g. via annotate_* methods).
However, valid use cases of this method include: - fine control of render (and clear) operations when yt plots are combined with plot
customizations other than plot callbacks (annotate_*)
testing
- save(name: str | list[str] | tuple[str, ...] | None = None, suffix: str | None = None, mpl_kwargs: dict[str, Any] | None = None)¶
saves the plot to disk.
- Parameters:
name (string or tuple, optional) – The base of the filename. If name is a directory or if name is not set, the filename of the dataset is used. For a tuple, the resulting path will be given by joining the elements of the tuple
suffix (string, optional) – Specify the image type by its suffix. If not specified, the output type will be inferred from the filename. Defaults to ‘.png’.
mpl_kwargs (dict, optional) – A dict of keyword arguments to be passed to matplotlib.
slc.save(mpl_kwargs={"bbox_inches" (>>>)
- set_antialias(aa)¶
Turn antialiasing on or off.
- Parameters:
aa (boolean)
- set_axes_unit(unit_name)¶
Set the unit for display on the x and y axes of the image.
- Parameters:
unit_name (string or two element tuple of strings) – A unit, available for conversion in the dataset, that the image extents will be displayed in. If set to None, any previous units will be reset. If the unit is None, the default is chosen. If unit_name is ‘1’, ‘u’, or ‘unitary’, it will not display the units, and only show the axes name. If unit_name is a tuple, the first element is assumed to be the unit for the x axis and the second element the unit for the y axis.
- Raises:
YTUnitNotRecognized – If the unit is not known, this will be raised.
Examples
>>> from yt import load >>> ds = load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> p = ProjectionPlot(ds, "y", "Density") >>> p.set_axes_unit("kpc")
- set_background_color(field, color=None)¶
set the background color to match provided color
- Parameters:
field (string) – the field to set the colormap if field == ‘all’, applies to all plots.
color (string or RGBA tuple (optional)) – if set, set the background color to this color if unset, background color is set to the bottom value of the color map
- set_buff_size(size)¶
Sets a new buffer size for the fixed resolution buffer
- Parameters:
size (int or two element sequence of ints) – The number of data elements in the buffer on the x and y axes. If a scalar is provided, then the buffer is assumed to be square.
- set_center(new_center, unit='code_length')¶
Sets a new center for the plot window
- Parameters:
new_center (two element sequence of floats) – The coordinates of the new center of the image in the coordinate system defined by the plot axes. If the unit keyword is not specified, the coordinates are assumed to be in code units.
unit (string) – The name of the unit new_center is given in. If new_center is a YTArray or tuple of YTQuantities, this keyword is ignored.
- set_cmap(field, cmap)¶
set the colormap for one of the fields
- Parameters:
field (string) – the field to set the colormap if field == ‘all’, applies to all plots.
cmap (string or tuple) – If a string, will be interpreted as name of the colormap. If a tuple, it is assumed to be of the form (name, type, number) to be used for palettable functionality. (name, type, number, bool) can be used to specify if a reverse colormap is to be used.
- set_colorbar_label(field, label)¶
Sets the colorbar label.
- set_colorbar_minorticks(field, state)¶
turn colorbar minor ticks on or off in the current plot
Displaying minor ticks reduces performance; turn them off using set_colorbar_minorticks(‘all’, False) if drawing speed is a problem.
- Parameters:
field (string) – the field to remove colorbar minorticks if field == ‘all’, applies to all plots.
state (bool) – the state indicating ‘on’ (True) or ‘off’ (False)
- set_figure_size(size)¶
Sets a new figure size for the plot
- Parameters:
size (float, a sequence of two floats, or None) – The size of the figure (in units of inches), including the margins but not the colorbar. If a single float is passed, it’s interpreted as the size along the long axis. Pass None to reset
- set_font(font_dict=None)¶
Set the font and font properties.
- Parameters:
font_dict (dict) –
A dict of keyword parameters to be passed to
matplotlib.font_manager.FontProperties
.Possible keys include:
family - The font family. Can be serif, sans-serif, cursive, ‘fantasy’ or ‘monospace’.
style - The font style. Either normal, italic or oblique.
color - A valid color string like ‘r’, ‘g’, ‘red’, ‘cobalt’, and ‘orange’.
variant - Either normal or small-caps.
size - Either a relative value of xx-small, x-small, small, medium, large, x-large, xx-large or an absolute font size, e.g. 12
stretch - A numeric value in the range 0-1000 or one of ultra-condensed, extra-condensed, condensed, semi-condensed, normal, semi-expanded, expanded, extra-expanded or ultra-expanded
weight - A numeric value in the range 0-1000 or one of ultralight, light, normal, regular, book, medium, roman, semibold, demibold, demi, bold, heavy, extra bold, or black
See the matplotlib font manager API documentation for more details. https://matplotlib.org/stable/api/font_manager_api.html
Notes
Mathtext axis labels will only obey the size and color keyword.
Examples
This sets the font to be 24-pt, blue, sans-serif, italic, and bold-face.
>>> slc = SlicePlot(ds, "x", "Density") >>> slc.set_font( ... { ... "family": "sans-serif", ... "style": "italic", ... "weight": "bold", ... "size": 24, ... "color": "blue", ... } ... )
- set_font_size(size)¶
Set the size of the font used in the plot
This sets the font size by calling the set_font function. See set_font for more font customization options.
- Parameters:
size (float)
inch). (The absolute size of the font in points (1 pt = 1/72)
- set_log(field, log: bool | None = None, *, linthresh: float | unyt_quantity | tuple[float, Unit | str] | Literal['auto'] | None = None, symlog_auto: bool | None = None)¶
set a field to log, linear, or symlog.
Symlog scaling is a combination of linear and log, where from 0 to a threshold value, it operates as linear, and then beyond that it operates as log. Symlog can also work with negative values in log space as well as negative and positive values simultaneously and symmetrically. If symlog scaling is desired, please set log=True and either set symlog_auto=True or select a value for linthresh.
- Parameters:
field (string) – the field to set a transform if field == ‘all’, applies to all plots.
log (boolean, optional) – set log to True for log scaling, False for linear scaling.
linthresh (float, (float, str), unyt_quantity, or 'auto', optional) – when using symlog scaling, linthresh is the value at which scaling transitions from linear to logarithmic. linthresh must be positive. Note: setting linthresh will automatically enable symlog scale
arguments (Note that log and linthresh are mutually exclusive)
- set_minorticks(field, state)¶
Turn minor ticks on or off in the current plot.
Displaying minor ticks reduces performance; turn them off using set_minorticks(‘all’, False) if drawing speed is a problem.
- Parameters:
field (string) – the field to remove minorticks if field == ‘all’, applies to all plots.
state (bool) – the state indicating ‘on’ (True) or ‘off’ (False)
- set_mpl_projection(mpl_proj)¶
Set the matplotlib projection type with a cartopy transform function
Given a string or a tuple argument, this will project the data onto the plot axes with the chosen transform function.
Assumes that the underlying data has a PlateCarree transform type.
To annotate the plot with coastlines or other annotations, render() will need to be called after this function to make the axes available for annotation.
- Parameters:
mpl_proj (string or tuple) – if passed as a string, mpl_proj is the specified projection type, if passed as a tuple, then tuple will take the form of
("ProjectionType", (args))
or("ProjectionType", (args), {kwargs})
Valid projection type options include: ‘PlateCarree’, ‘LambertConformal’, ‘LabmbertCylindrical’, ‘Mercator’, ‘Miller’, ‘Mollweide’, ‘Orthographic’, ‘Robinson’, ‘Stereographic’, ‘TransverseMercator’, ‘InterruptedGoodeHomolosine’, ‘RotatedPole’, ‘OGSB’, ‘EuroPP’, ‘Geostationary’, ‘Gnomonic’, ‘NorthPolarStereo’, ‘OSNI’, ‘SouthPolarStereo’, ‘AlbersEqualArea’, ‘AzimuthalEquidistant’, ‘Sinusoidal’, ‘UTM’, ‘NearsidePerspective’, ‘LambertAzimuthalEqualArea’
Examples
This will create a Mollweide projection using Mollweide default values and annotate it with coastlines
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection("AIRDENS", "Mollweide") >>> p.render() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will move the PlateCarree central longitude to 90 degrees and annotate with coastlines.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection( ... "AIRDENS", ("PlateCarree", (), {"central_longitude": 90, "globe": None}) ... ) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will create a RoatatedPole projection with the unrotated pole position at 37.5 degrees latitude and 177.5 degrees longitude by passing them in as args.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection("RotatedPole", (177.5, 37.5)) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will create a RoatatedPole projection with the unrotated pole position at 37.5 degrees latitude and 177.5 degrees longitude by passing them in as kwargs.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection( ... ("RotatedPole", (), {"pole_latitude": 37.5, "pole_longitude": 177.5}) ... ) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
- set_norm(field, norm: Normalize)¶
Set a custom
matplotlib.colors.Normalize
to plot field.Any constraints previously set with set_log, set_zlim will be dropped.
Note that any float value attached to norm (e.g. vmin, vmax, vcenter …) will be read in the current displayed units, which can be controlled with the set_unit method.
- Parameters:
field (str or tuple[str, str]) – if field == ‘all’, applies to all plots.
norm (matplotlib.colors.Normalize) – see https://matplotlib.org/stable/tutorials/colors/colormapnorms.html
- set_origin(origin)¶
Set the plot origin.
- Parameters:
origin (string or length 1, 2, or 3 sequence.) – The location of the origin of the plot coordinate system. This is typically represented by a ‘-’ separated string or a tuple of strings. In the first index the y-location is given by ‘lower’, ‘upper’, or ‘center’. The second index is the x-location, given as ‘left’, ‘right’, or ‘center’. Finally, whether the origin is applied in ‘domain’ space, plot ‘window’ space or ‘native’ simulation coordinate system is given. For example, both ‘upper-right-domain’ and [‘upper’, ‘right’, ‘domain’] place the origin in the upper right hand corner of domain space. If x or y are not given, a value is inferred. For instance, ‘left-domain’ corresponds to the lower-left hand corner of the simulation domain, ‘center-domain’ corresponds to the center of the simulation domain, or ‘center-window’ for the center of the plot window. In the event that none of these options place the origin in a desired location, a sequence of tuples and a string specifying the coordinate space can be given. If plain numeric types are input, units of code_length are assumed. Further examples:
=============================== (===============================================)
example (format)
===============================
'domain' ('{space}')
'left-window' ('{xloc}-{space}')
'upper-domain' ('{yloc}-{space}')
'lower-right-window' ('{yloc}-{xloc}-{space}')
('{space}'
('window' ())
)
('{xloc}'
('right' ('{space}'))
'domain')
('{yloc}'
('lower' ('{space}'))
'window')
('{yloc}'
'{xloc}'
('lower'
'right'
'window')
((yloc
'{unit}')
(xloc
'{unit}')
((0 ('{space}'))
'm')
(.4
'm')
'window')
(xloc
yloc
(0.23 ('{space}'))
0.5
'domain')
===============================
- set_unit(field, new_unit, equivalency=None, equivalency_kwargs=None)¶
Sets a new unit for the requested field
- Parameters:
field (string or field tuple) – The name of the field that is to be changed.
new_unit (string or Unit object)
equivalency (string, optional) – If set, the equivalency to use to convert the current units to the new requested unit. If None, the unit conversion will be done without an equivalency
equivalency_kwargs (string, optional) – Keyword arguments to be passed to the equivalency. Only used if
equivalency
is set.
- set_width(width, unit=None)¶
set the width of the plot window
- Parameters:
width (float, array of floats, (float, unit) tuple, or tuple of) –
(float, unit) tuples.
Width can have four different formats to support windows with variable x and y widths. They are:
format
example
(float, string)
(10,’kpc’)
((float, string), (float, string))
((10,’kpc’),(15,’kpc’))
float
0.2
(float, float)
(0.2, 0.3)
For example, (10, ‘kpc’) requests a plot window that is 10 kiloparsecs wide in the x and y directions, ((10,’kpc’),(15,’kpc’)) requests a window that is 10 kiloparsecs wide along the x axis and 15 kiloparsecs wide along the y axis. In the other two examples, code units are assumed, for example (0.2, 0.3) requests a plot that has an x width of 0.2 and a y width of 0.3 in code units. If units are provided the resulting plot axis labels will use the supplied units.
unit (str) – the unit the width has been specified in. If width is a tuple, this argument is ignored. Defaults to code units.
- set_xlabel(label)¶
Allow the user to modify the X-axis title Defaults to the global value. Fontsize defaults to 18.
- Parameters:
label (str) – The new string for the x-axis.
(cm$^{-3}$)") (>>> plot.set_xlabel("H2I Number Density)
- set_ylabel(label)¶
Allow the user to modify the Y-axis title Defaults to the global value.
- Parameters:
label (str) – The new string for the y-axis.
(K)") (>>> plot.set_ylabel("Temperature)
- set_zlim(field, zmin: ~unyt.array.unyt_quantity | tuple[float, ~unyt.unit_object.Unit | str] | float | ~typing.Literal['min'] | ~yt.visualization.plot_container.Unset = <yt.visualization.plot_container.Unset object>, zmax: ~unyt.array.unyt_quantity | tuple[float, ~unyt.unit_object.Unit | str] | float | ~typing.Literal['max'] | ~yt.visualization.plot_container.Unset = <yt.visualization.plot_container.Unset object>, dynamic_range: float | None = None)¶
set the scale of the colormap
- Parameters:
field (string) – the field to set a colormap scale if field == ‘all’, applies to all plots.
zmin (float, Quantity, or 'min') – the new minimum of the colormap scale. If ‘min’, will set to the minimum value in the current view.
zmax (float, Quantity, or 'max') – the new maximum of the colormap scale. If ‘max’, will set to the maximum value in the current view.
dynamic_range (float (default: None)) – The dynamic range of the image. If zmin == None, will set zmin = zmax / dynamic_range If zmax == None, will set zmax = zmin * dynamic_range
- show()¶
This will send any existing plots to the IPython notebook.
If yt is being run from within an IPython session, and it is able to determine this, this function will send any existing plots to the notebook for display.
If yt can’t determine if it’s inside an IPython session, it will raise YTNotInsideNotebook.
Examples
>>> from yt import SlicePlot >>> slc = SlicePlot( ... ds, "x", [("gas", "density"), ("gas", "velocity_magnitude")] ... ) >>> slc.show()
- show_axes(field=None)¶
Shows the axes for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object. See hide_axes().
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to show the axes.
- show_colorbar(field=None)¶
Shows the colorbar for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object. See hide_colorbar().
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional))
colorbar. (The name of the field(s) that we want to show the)
- swap_axes()¶
- to_fits_data(fields=None, other_keys=None, length_unit=None, **kwargs)¶
Export the fields in this PlotWindow instance to a FITSImageData instance.
This will export a set of FITS images of either the fields specified or all the fields already in the object.
- Parameters:
fields (list of strings) – These fields will be pixelized and output. If “None”, the keys of the FRB will be used.
other_keys (dictionary, optional) – A set of header keys and values to write into the FITS header.
length_unit (string, optional) – the length units that the coordinates are written in. The default is to use the default length unit of the dataset.
- property width¶
- class yt.visualization.plot_window.PlotWindow(data_source, bounds, buff_size=(800, 800), antialias=True, periodic=True, origin='center-window', oblique=False, window_size=8.0, fields=None, fontsize=18, aspect=None, setup=False, *, geometry: Geometry = Geometry.CARTESIAN)[source]¶
Bases:
ImagePlotContainer
,ABC
A plotting mechanism based around the concept of a window into a data source. It can have arbitrary fields, each of which will be centered on the same viewpoint, but will have individual zlimits.
The data and plot are updated separately, and each can be invalidated as the object is modified.
Data is handled by a FixedResolutionBuffer object.
- Parameters:
data_source –
yt.data_objects.selection_objects.base_objects.YTSelectionContainer2D
This is the source to be pixelized, which can be a projection, slice, or a cutting plane.bounds (sequence of floats) – Bounds are the min and max in the image plane that we want our image to cover. It’s in the order of (xmin, xmax, ymin, ymax), where the coordinates are all in the appropriate code units.
buff_size (sequence of ints) – The size of the image to generate.
antialias (boolean) – This can be true or false. It determines whether or not sub-pixel rendering is used during data deposition.
window_size (float) – The size of the window on the longest axis (in units of inches), including the margins but not the colorbar.
- property bounds¶
- display(name=None, mpl_kwargs=None)¶
Will attempt to show the plot in in an IPython notebook. Failing that, the plot will be saved to disk.
- property frb¶
- get_log(field)¶
get the transform type of a field.
- Parameters:
field (string) – the field to get a transform if field == ‘all’, applies to all plots.
- hide_axes(field=None, draw_frame=None)¶
Hides the axes for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object.
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to hide the axes.
draw_frame (boolean) – If True, the axes frame will still be drawn. Defaults to False. See note below for more details.
Examples
This will save an image with no axes.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.save()
This will save an image with no axis or colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.hide_colorbar() >>> s.save()
Note
By default, when removing the axes, the patch on which the axes are drawn is disabled, making it impossible to later change e.g. the background colour. To force the axes patch to be displayed while still hiding the axes, set the
draw_frame
keyword argument toTrue
.
- hide_colorbar(field=None)¶
Hides the colorbar for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object.
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to hide the colorbar. If None or ‘all’ is provided, will default to using all fields available for this object.
Examples
This will save an image with no colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_colorbar() >>> s.save()
This will save an image with no axis or colorbar.
>>> import yt >>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> s = SlicePlot(ds, 2, "density", "c", (20, "kpc")) >>> s.hide_axes() >>> s.hide_colorbar() >>> s.save()
- pan(deltas)[source]¶
Pan the image by specifying absolute code unit coordinate deltas.
- Parameters:
deltas (Two-element sequence of floats, quantities, or (float, unit)) –
tuples.
(delta_x, delta_y). If a unit is not supplied the unit is assumed to be code_length.
- pan_rel(deltas)[source]¶
Pan the image by specifying relative deltas, to the FOV.
- Parameters:
deltas (sequence of floats) – (delta_x, delta_y) in relative code unit coordinates
- refresh()¶
- render() None ¶
Render plots. This operation is expensive and usually doesn’t need to be requested explicitly. In most cases, yt handles rendering automatically and delays it as much as possible to avoid redundant calls on each plot modification (e.g. via annotate_* methods).
However, valid use cases of this method include: - fine control of render (and clear) operations when yt plots are combined with plot
customizations other than plot callbacks (annotate_*)
testing
- save(name: str | list[str] | tuple[str, ...] | None = None, suffix: str | None = None, mpl_kwargs: dict[str, Any] | None = None)¶
saves the plot to disk.
- Parameters:
name (string or tuple, optional) – The base of the filename. If name is a directory or if name is not set, the filename of the dataset is used. For a tuple, the resulting path will be given by joining the elements of the tuple
suffix (string, optional) – Specify the image type by its suffix. If not specified, the output type will be inferred from the filename. Defaults to ‘.png’.
mpl_kwargs (dict, optional) – A dict of keyword arguments to be passed to matplotlib.
slc.save(mpl_kwargs={"bbox_inches" (>>>)
- set_axes_unit(unit_name)[source]¶
Set the unit for display on the x and y axes of the image.
- Parameters:
unit_name (string or two element tuple of strings) – A unit, available for conversion in the dataset, that the image extents will be displayed in. If set to None, any previous units will be reset. If the unit is None, the default is chosen. If unit_name is ‘1’, ‘u’, or ‘unitary’, it will not display the units, and only show the axes name. If unit_name is a tuple, the first element is assumed to be the unit for the x axis and the second element the unit for the y axis.
- Raises:
YTUnitNotRecognized – If the unit is not known, this will be raised.
Examples
>>> from yt import load >>> ds = load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> p = ProjectionPlot(ds, "y", "Density") >>> p.set_axes_unit("kpc")
- set_background_color(field, color=None)¶
set the background color to match provided color
- Parameters:
field (string) – the field to set the colormap if field == ‘all’, applies to all plots.
color (string or RGBA tuple (optional)) – if set, set the background color to this color if unset, background color is set to the bottom value of the color map
- set_buff_size(size)[source]¶
Sets a new buffer size for the fixed resolution buffer
- Parameters:
size (int or two element sequence of ints) – The number of data elements in the buffer on the x and y axes. If a scalar is provided, then the buffer is assumed to be square.
- set_center(new_center, unit='code_length')[source]¶
Sets a new center for the plot window
- Parameters:
new_center (two element sequence of floats) – The coordinates of the new center of the image in the coordinate system defined by the plot axes. If the unit keyword is not specified, the coordinates are assumed to be in code units.
unit (string) – The name of the unit new_center is given in. If new_center is a YTArray or tuple of YTQuantities, this keyword is ignored.
- set_cmap(field, cmap)¶
set the colormap for one of the fields
- Parameters:
field (string) – the field to set the colormap if field == ‘all’, applies to all plots.
cmap (string or tuple) – If a string, will be interpreted as name of the colormap. If a tuple, it is assumed to be of the form (name, type, number) to be used for palettable functionality. (name, type, number, bool) can be used to specify if a reverse colormap is to be used.
- set_colorbar_label(field, label)¶
Sets the colorbar label.
- set_colorbar_minorticks(field, state)¶
turn colorbar minor ticks on or off in the current plot
Displaying minor ticks reduces performance; turn them off using set_colorbar_minorticks(‘all’, False) if drawing speed is a problem.
- Parameters:
field (string) – the field to remove colorbar minorticks if field == ‘all’, applies to all plots.
state (bool) – the state indicating ‘on’ (True) or ‘off’ (False)
- set_figure_size(size)¶
Sets a new figure size for the plot
- Parameters:
size (float, a sequence of two floats, or None) – The size of the figure (in units of inches), including the margins but not the colorbar. If a single float is passed, it’s interpreted as the size along the long axis. Pass None to reset
- set_font(font_dict=None)¶
Set the font and font properties.
- Parameters:
font_dict (dict) –
A dict of keyword parameters to be passed to
matplotlib.font_manager.FontProperties
.Possible keys include:
family - The font family. Can be serif, sans-serif, cursive, ‘fantasy’ or ‘monospace’.
style - The font style. Either normal, italic or oblique.
color - A valid color string like ‘r’, ‘g’, ‘red’, ‘cobalt’, and ‘orange’.
variant - Either normal or small-caps.
size - Either a relative value of xx-small, x-small, small, medium, large, x-large, xx-large or an absolute font size, e.g. 12
stretch - A numeric value in the range 0-1000 or one of ultra-condensed, extra-condensed, condensed, semi-condensed, normal, semi-expanded, expanded, extra-expanded or ultra-expanded
weight - A numeric value in the range 0-1000 or one of ultralight, light, normal, regular, book, medium, roman, semibold, demibold, demi, bold, heavy, extra bold, or black
See the matplotlib font manager API documentation for more details. https://matplotlib.org/stable/api/font_manager_api.html
Notes
Mathtext axis labels will only obey the size and color keyword.
Examples
This sets the font to be 24-pt, blue, sans-serif, italic, and bold-face.
>>> slc = SlicePlot(ds, "x", "Density") >>> slc.set_font( ... { ... "family": "sans-serif", ... "style": "italic", ... "weight": "bold", ... "size": 24, ... "color": "blue", ... } ... )
- set_font_size(size)¶
Set the size of the font used in the plot
This sets the font size by calling the set_font function. See set_font for more font customization options.
- Parameters:
size (float)
inch). (The absolute size of the font in points (1 pt = 1/72)
- set_log(field, log: bool | None = None, *, linthresh: float | unyt_quantity | tuple[float, Unit | str] | Literal['auto'] | None = None, symlog_auto: bool | None = None)¶
set a field to log, linear, or symlog.
Symlog scaling is a combination of linear and log, where from 0 to a threshold value, it operates as linear, and then beyond that it operates as log. Symlog can also work with negative values in log space as well as negative and positive values simultaneously and symmetrically. If symlog scaling is desired, please set log=True and either set symlog_auto=True or select a value for linthresh.
- Parameters:
field (string) – the field to set a transform if field == ‘all’, applies to all plots.
log (boolean, optional) – set log to True for log scaling, False for linear scaling.
linthresh (float, (float, str), unyt_quantity, or 'auto', optional) – when using symlog scaling, linthresh is the value at which scaling transitions from linear to logarithmic. linthresh must be positive. Note: setting linthresh will automatically enable symlog scale
arguments (Note that log and linthresh are mutually exclusive)
- set_minorticks(field, state)¶
Turn minor ticks on or off in the current plot.
Displaying minor ticks reduces performance; turn them off using set_minorticks(‘all’, False) if drawing speed is a problem.
- Parameters:
field (string) – the field to remove minorticks if field == ‘all’, applies to all plots.
state (bool) – the state indicating ‘on’ (True) or ‘off’ (False)
- set_mpl_projection(mpl_proj)[source]¶
Set the matplotlib projection type with a cartopy transform function
Given a string or a tuple argument, this will project the data onto the plot axes with the chosen transform function.
Assumes that the underlying data has a PlateCarree transform type.
To annotate the plot with coastlines or other annotations, render() will need to be called after this function to make the axes available for annotation.
- Parameters:
mpl_proj (string or tuple) – if passed as a string, mpl_proj is the specified projection type, if passed as a tuple, then tuple will take the form of
("ProjectionType", (args))
or("ProjectionType", (args), {kwargs})
Valid projection type options include: ‘PlateCarree’, ‘LambertConformal’, ‘LabmbertCylindrical’, ‘Mercator’, ‘Miller’, ‘Mollweide’, ‘Orthographic’, ‘Robinson’, ‘Stereographic’, ‘TransverseMercator’, ‘InterruptedGoodeHomolosine’, ‘RotatedPole’, ‘OGSB’, ‘EuroPP’, ‘Geostationary’, ‘Gnomonic’, ‘NorthPolarStereo’, ‘OSNI’, ‘SouthPolarStereo’, ‘AlbersEqualArea’, ‘AzimuthalEquidistant’, ‘Sinusoidal’, ‘UTM’, ‘NearsidePerspective’, ‘LambertAzimuthalEqualArea’
Examples
This will create a Mollweide projection using Mollweide default values and annotate it with coastlines
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection("AIRDENS", "Mollweide") >>> p.render() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will move the PlateCarree central longitude to 90 degrees and annotate with coastlines.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection( ... "AIRDENS", ("PlateCarree", (), {"central_longitude": 90, "globe": None}) ... ) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will create a RoatatedPole projection with the unrotated pole position at 37.5 degrees latitude and 177.5 degrees longitude by passing them in as args.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection("RotatedPole", (177.5, 37.5)) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
This will create a RoatatedPole projection with the unrotated pole position at 37.5 degrees latitude and 177.5 degrees longitude by passing them in as kwargs.
>>> import yt >>> ds = yt.load("") >>> p = yt.SlicePlot(ds, "altitude", "AIRDENS") >>> p.set_mpl_projection( ... ("RotatedPole", (), {"pole_latitude": 37.5, "pole_longitude": 177.5}) ... ) >>> p.render() >>> p.plots["AIRDENS"].axes.set_global() >>> p.plots["AIRDENS"].axes.coastlines() >>> p.show()
- set_norm(field, norm: Normalize)¶
Set a custom
matplotlib.colors.Normalize
to plot field.Any constraints previously set with set_log, set_zlim will be dropped.
Note that any float value attached to norm (e.g. vmin, vmax, vcenter …) will be read in the current displayed units, which can be controlled with the set_unit method.
- Parameters:
field (str or tuple[str, str]) – if field == ‘all’, applies to all plots.
norm (matplotlib.colors.Normalize) – see https://matplotlib.org/stable/tutorials/colors/colormapnorms.html
- set_origin(origin)[source]¶
Set the plot origin.
- Parameters:
origin (string or length 1, 2, or 3 sequence.) – The location of the origin of the plot coordinate system. This is typically represented by a ‘-’ separated string or a tuple of strings. In the first index the y-location is given by ‘lower’, ‘upper’, or ‘center’. The second index is the x-location, given as ‘left’, ‘right’, or ‘center’. Finally, whether the origin is applied in ‘domain’ space, plot ‘window’ space or ‘native’ simulation coordinate system is given. For example, both ‘upper-right-domain’ and [‘upper’, ‘right’, ‘domain’] place the origin in the upper right hand corner of domain space. If x or y are not given, a value is inferred. For instance, ‘left-domain’ corresponds to the lower-left hand corner of the simulation domain, ‘center-domain’ corresponds to the center of the simulation domain, or ‘center-window’ for the center of the plot window. In the event that none of these options place the origin in a desired location, a sequence of tuples and a string specifying the coordinate space can be given. If plain numeric types are input, units of code_length are assumed. Further examples:
=============================== (===============================================)
example (format)
===============================
'domain' ('{space}')
'left-window' ('{xloc}-{space}')
'upper-domain' ('{yloc}-{space}')
'lower-right-window' ('{yloc}-{xloc}-{space}')
('{space}'
('window' ())
)
('{xloc}'
('right' ('{space}'))
'domain')
('{yloc}'
('lower' ('{space}'))
'window')
('{yloc}'
'{xloc}'
('lower'
'right'
'window')
((yloc
'{unit}')
(xloc
'{unit}')
((0 ('{space}'))
'm')
(.4
'm')
'window')
(xloc
yloc
(0.23 ('{space}'))
0.5
'domain')
===============================
- set_unit(field, new_unit, equivalency=None, equivalency_kwargs=None)[source]¶
Sets a new unit for the requested field
- Parameters:
field (string or field tuple) – The name of the field that is to be changed.
new_unit (string or Unit object)
equivalency (string, optional) – If set, the equivalency to use to convert the current units to the new requested unit. If None, the unit conversion will be done without an equivalency
equivalency_kwargs (string, optional) – Keyword arguments to be passed to the equivalency. Only used if
equivalency
is set.
- set_width(width, unit=None)[source]¶
set the width of the plot window
- Parameters:
width (float, array of floats, (float, unit) tuple, or tuple of) –
(float, unit) tuples.
Width can have four different formats to support windows with variable x and y widths. They are:
format
example
(float, string)
(10,’kpc’)
((float, string), (float, string))
((10,’kpc’),(15,’kpc’))
float
0.2
(float, float)
(0.2, 0.3)
For example, (10, ‘kpc’) requests a plot window that is 10 kiloparsecs wide in the x and y directions, ((10,’kpc’),(15,’kpc’)) requests a window that is 10 kiloparsecs wide along the x axis and 15 kiloparsecs wide along the y axis. In the other two examples, code units are assumed, for example (0.2, 0.3) requests a plot that has an x width of 0.2 and a y width of 0.3 in code units. If units are provided the resulting plot axis labels will use the supplied units.
unit (str) – the unit the width has been specified in. If width is a tuple, this argument is ignored. Defaults to code units.
- set_xlabel(label)¶
Allow the user to modify the X-axis title Defaults to the global value. Fontsize defaults to 18.
- Parameters:
label (str) – The new string for the x-axis.
(cm$^{-3}$)") (>>> plot.set_xlabel("H2I Number Density)
- set_ylabel(label)¶
Allow the user to modify the Y-axis title Defaults to the global value.
- Parameters:
label (str) – The new string for the y-axis.
(K)") (>>> plot.set_ylabel("Temperature)
- set_zlim(field, zmin: ~unyt.array.unyt_quantity | tuple[float, ~unyt.unit_object.Unit | str] | float | ~typing.Literal['min'] | ~yt.visualization.plot_container.Unset = <yt.visualization.plot_container.Unset object>, zmax: ~unyt.array.unyt_quantity | tuple[float, ~unyt.unit_object.Unit | str] | float | ~typing.Literal['max'] | ~yt.visualization.plot_container.Unset = <yt.visualization.plot_container.Unset object>, dynamic_range: float | None = None)¶
set the scale of the colormap
- Parameters:
field (string) – the field to set a colormap scale if field == ‘all’, applies to all plots.
zmin (float, Quantity, or 'min') – the new minimum of the colormap scale. If ‘min’, will set to the minimum value in the current view.
zmax (float, Quantity, or 'max') – the new maximum of the colormap scale. If ‘max’, will set to the maximum value in the current view.
dynamic_range (float (default: None)) – The dynamic range of the image. If zmin == None, will set zmin = zmax / dynamic_range If zmax == None, will set zmax = zmin * dynamic_range
- show()¶
This will send any existing plots to the IPython notebook.
If yt is being run from within an IPython session, and it is able to determine this, this function will send any existing plots to the notebook for display.
If yt can’t determine if it’s inside an IPython session, it will raise YTNotInsideNotebook.
Examples
>>> from yt import SlicePlot >>> slc = SlicePlot( ... ds, "x", [("gas", "density"), ("gas", "velocity_magnitude")] ... ) >>> slc.show()
- show_axes(field=None)¶
Shows the axes for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object. See hide_axes().
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional)) – The name of the field(s) that we want to show the axes.
- show_colorbar(field=None)¶
Shows the colorbar for a plot and updates the size of the plot accordingly. Defaults to operating on all fields for a PlotContainer object. See hide_colorbar().
- Parameters:
field (string, field tuple, or list of strings or field tuples (optional))
colorbar. (The name of the field(s) that we want to show the)
- to_fits_data(fields=None, other_keys=None, length_unit=None, **kwargs)[source]¶
Export the fields in this PlotWindow instance to a FITSImageData instance.
This will export a set of FITS images of either the fields specified or all the fields already in the object.
- Parameters:
fields (list of strings) – These fields will be pixelized and output. If “None”, the keys of the FRB will be used.
other_keys (dictionary, optional) – A set of header keys and values to write into the FITS header.
length_unit (string, optional) – the length units that the coordinates are written in. The default is to use the default length unit of the dataset.
- property width¶
- class yt.visualization.plot_window.ProjectionPlot(ds, normal, fields, *args, **kwargs)[source]¶
Bases:
NormalPlot
A dispatch class for
yt.visualization.plot_window.AxisAlignedProjectionPlot
andyt.visualization.plot_window.OffAxisProjectionPlot
objects. This essentially allows for a single entry point to both types of projection plots, the distinction being determined by the specified normal vector to the slice.The returned plot object can be updated using one of the many helper functions defined in PlotWindow.
- Parameters:
ds (
yt.data_objects.static_output.Dataset
) – This is the dataset object corresponding to the simulation output to be plotted.normal (int, str, or 3-element sequence of floats) –
This specifies the normal vector to the projection. Valid int values are 0, 1 and 2. Corresponding str values depend on the geometry of the dataset and are generally given by ds.coordinates.axis_order. E.g. in cartesian they are ‘x’, ‘y’ and ‘z’. An arbitrary normal vector may be specified as a 3-element sequence of floats.
This function will return a
OffAxisProjectionPlot
object or aAxisAlignedProjectionPlot
object, depending on whether the requested normal directions corresponds to a natural axis of the dataset’s geometry.fields (a (or a list of) 2-tuple of strings (ftype, fname)) – The name of the field(s) to be plotted.
Any additional positional and keyword arguments are passed down to the appropriate return class. See
yt.visualization.plot_window.AxisAlignedProjectionPlot
andyt.visualization.plot_window.OffAxisProjectionPlot
.- Raises:
ValueError or TypeError – If normal cannot be interpreted as a valid normal direction.
- class yt.visualization.plot_window.SlicePlot(ds, normal, fields, *args, **kwargs)[source]¶
Bases:
NormalPlot
A dispatch class for
yt.visualization.plot_window.AxisAlignedSlicePlot
andyt.visualization.plot_window.OffAxisSlicePlot
objects. This essentially allows for a single entry point to both types of slice plots, the distinction being determined by the specified normal vector to the projection.The returned plot object can be updated using one of the many helper functions defined in PlotWindow.
- Parameters:
ds (
yt.data_objects.static_output.Dataset
) – This is the dataset object corresponding to the simulation output to be plotted.normal (int, str, or 3-element sequence of floats) –
This specifies the normal vector to the slice. Valid int values are 0, 1 and 2. Corresponding str values depend on the geometry of the dataset and are generally given by ds.coordinates.axis_order. E.g. in cartesian they are ‘x’, ‘y’ and ‘z’. An arbitrary normal vector may be specified as a 3-element sequence of floats.
This returns a
OffAxisSlicePlot
object or aAxisAlignedSlicePlot
object, depending on whether the requested normal directions corresponds to a natural axis of the dataset’s geometry.fields (a (or a list of) 2-tuple of strings (ftype, fname)) – The name of the field(s) to be plotted.
respective (The following are nominally keyword arguments passed onto the)
function. (slice plot objects generated by this)
- Keyword Arguments:
center ('center', 'c', 'left', 'l', 'right', 'r', id of a global extremum, or array-like) –
The coordinate of the selection’s center. Defaults to the ‘center’, i.e. center of the domain.
Centering on the min or max of a field is supported by passing a tuple such as (‘min’, (‘gas’, ‘density’)) or (‘max’, (‘gas’, ‘temperature’). A single string may also be used (e.g. “min_density” or “max_temperature”), though it’s not as flexible and does not allow to select an exact field/particle type. With this syntax, the first field matching the provided name is selected. ‘max’ or ‘m’ can be used as a shortcut for (‘max’, (‘gas’, ‘density’)) ‘min’ can be used as a shortcut for (‘min’, (‘gas’, ‘density’))
One can also select an exact point as a 3 element coordinate sequence, e.g. [0.5, 0.5, 0] Units can be specified by passing in center as a tuple containing a 3-element coordinate sequence and string unit name, e.g. ([0, 0.5, 0.5], “cm”), or by passing in a YTArray. Code units are assumed if unspecified.
The domain edges along the selected axis can be selected with ‘left’/’l’ and ‘right’/’r’ respectively.
width (tuple or a float.) –
Width can have four different formats to support windows with variable x and y widths. They are:
format
example
(float, string)
(10,’kpc’)
((float, string), (float, string))
((10,’kpc’),(15,’kpc’))
float
0.2
(float, float)
(0.2, 0.3)
For example, (10, ‘kpc’) requests a plot window that is 10 kiloparsecs wide in the x and y directions, ((10,’kpc’),(15,’kpc’)) requests a window that is 10 kiloparsecs wide along the x axis and 15 kiloparsecs wide along the y axis. In the other two examples, code units are assumed, for example (0.2, 0.3) requests a plot that has an x width of 0.2 and a y width of 0.3 in code units. If units are provided the resulting plot axis labels will use the supplied units.
axes_unit (string) – The name of the unit for the tick labels on the x and y axes. Defaults to None, which automatically picks an appropriate unit. If axes_unit is ‘1’, ‘u’, or ‘unitary’, it will not display the units, and only show the axes name.
origin (string or length 1, 2, or 3 sequence.) –
The location of the origin of the plot coordinate system for AxisAlignedSlicePlot object; for OffAxisSlicePlot objects this parameter is discarded. This is typically represented by a ‘-’ separated string or a tuple of strings. In the first index the y-location is given by ‘lower’, ‘upper’, or ‘center’. The second index is the x-location, given as ‘left’, ‘right’, or ‘center’. Finally, the whether the origin is applied in ‘domain’ space, plot ‘window’ space or ‘native’ simulation coordinate system is given. For example, both ‘upper-right-domain’ and [‘upper’, ‘right’, ‘domain’] place the origin in the upper right hand corner of domain space. If x or y are not given, a value is inferred. For instance, ‘left-domain’ corresponds to the lower-left hand corner of the simulation domain, ‘center-domain’ corresponds to the center of the simulation domain, or ‘center-window’ for the center of the plot window. In the event that none of these options place the origin in a desired location, a sequence of tuples and a string specifying the coordinate space can be given. If plain numeric types are input, units of code_length are assumed. Further examples:
format
example
’{space}’
’domain’
’{xloc}-{space}’
’left-window’
’{yloc}-{space}’
’upper-domain’
’{yloc}-{xloc}-{space}’
’lower-right-window’
(‘{space}’,)
(‘window’,)
(‘{xloc}’, ‘{space}’)
(‘right’, ‘domain’)
(‘{yloc}’, ‘{space}’)
(‘lower’, ‘window’)
(‘{yloc}’, ‘{xloc}’, ‘{space}’)
(‘lower’, ‘right’, ‘window’)
((yloc, ‘{unit}’), (xloc, ‘{unit}’), ‘{space}’)
((0, ‘m’), (.4, ‘m’), ‘window’)
(xloc, yloc, ‘{space}’)
(0.23, 0.5, ‘domain’)
north_vector (a sequence of floats) – A vector defining the ‘up’ direction in the OffAxisSlicePlot; not used in AxisAlignedSlicePlot. This option sets the orientation of the slicing plane. If not set, an arbitrary grid-aligned north-vector is chosen.
fontsize (integer) – The size of the fonts for the axis, colorbar, and tick labels.
field_parameters (dictionary) – A dictionary of field parameters than can be accessed by derived fields.
data_source (YTSelectionContainer Object) – Object to be used for data selection. Defaults to a region covering the entire simulation.
swap_axes (bool)
- Raises:
ValueError or TypeError – If normal cannot be interpreted as a valid normal direction.
Examples
>>> from yt import load >>> ds = load("IsolatedGalaxy/galaxy0030/galaxy0030") >>> slc = SlicePlot(ds, "x", ("gas", "density"), center=[0.2, 0.3, 0.4])
>>> slc = SlicePlot( ... ds, [0.4, 0.2, -0.1], ("gas", "pressure"), north_vector=[0.2, -0.3, 0.1] ... )
- class yt.visualization.plot_window.WindowPlotMPL(data, extent, figure_size, fontsize, aspect, figure, axes, cax, mpl_proj, mpl_transform, *, norm_handler: NormHandler, colorbar_handler: ColorbarHandler, alpha: np.ndarray[Any, np.dtype[np.float64]] | None = None)[source]¶
Bases:
ImagePlotMPL
A container for a single PlotWindow matplotlib figure and axes
- hide_axes(*, draw_frame=None)¶
Hide the axes for a plot including ticks and labels
- hide_colorbar()¶
Hide the colorbar for a plot including ticks and labels
- save(name, mpl_kwargs=None, canvas=None)¶
Choose backend and save image to disk
- show()¶
- show_axes()¶
Show the axes for a plot including ticks and labels
- show_colorbar()¶
Show the colorbar for a plot including ticks and labels
- yt.visualization.plot_window.get_axes_unit(width, ds)[source]¶
Infers the axes unit names from the input width specification
- yt.visualization.plot_window.get_oblique_window_parameters(normal, center, width, ds, depth=None, get3bounds=False)[source]¶
- yt.visualization.plot_window.plot_2d(ds, fields, center='center', width=None, axes_unit=None, origin='center-window', fontsize=18, field_parameters=None, window_size=8.0, aspect=None, data_source=None) AxisAlignedSlicePlot [source]¶
Creates a plot of a 2D dataset
Given a ds object and a field name string, this will return a PWViewerMPL object containing the plot.
The plot can be updated using one of the many helper functions defined in PlotWindow.
- Parameters:
ds (Dataset) – This is the dataset object corresponding to the simulation output to be plotted.
fields (string) – The name of the field(s) to be plotted.
center ('center', 'c', id of a global extremum, or array-like) –
The coordinate of the selection’s center. Defaults to the ‘center’, i.e. center of the domain.
Centering on the min or max of a field is supported by passing a tuple such as (‘min’, (‘gas’, ‘density’)) or (‘max’, (‘gas’, ‘temperature’). A single string may also be used (e.g. “min_density” or “max_temperature”), though it’s not as flexible and does not allow to select an exact field/particle type. With this syntax, the first field matching the provided name is selected. ‘max’ or ‘m’ can be used as a shortcut for (‘max’, (‘gas’, ‘density’)) ‘min’ can be used as a shortcut for (‘min’, (‘gas’, ‘density’))
One can also select an exact point as a 3 element coordinate sequence, e.g. [0.5, 0.5, 0] Units can be specified by passing in center as a tuple containing a 3-element coordinate sequence and string unit name, e.g. ([0, 0.5, 0.5], “cm”), or by passing in a YTArray. Code units are assumed if unspecified.
plot_2d also accepts a coordinate in two dimensions.
width (tuple or a float.) –
Width can have four different formats to support windows with variable x and y widths. They are:
format
example
(float, string)
(10,’kpc’)
((float, string), (float, string))
((10,’kpc’),(15,’kpc’))
float
0.2
(float, float)
(0.2, 0.3)
For example, (10, ‘kpc’) requests a plot window that is 10 kiloparsecs wide in the x and y directions, ((10,’kpc’),(15,’kpc’)) requests a window that is 10 kiloparsecs wide along the x axis and 15 kiloparsecs wide along the y axis. In the other two examples, code units are assumed, for example (0.2, 0.3) requests a plot that has an x width of 0.2 and a y width of 0.3 in code units. If units are provided the resulting plot axis labels will use the supplied units.
origin (string or length 1, 2, or 3 sequence.) –
The location of the origin of the plot coordinate system. This is typically represented by a ‘-’ separated string or a tuple of strings. In the first index the y-location is given by ‘lower’, ‘upper’, or ‘center’. The second index is the x-location, given as ‘left’, ‘right’, or ‘center’. Finally, whether the origin is applied in ‘domain’ space, plot ‘window’ space or ‘native’ simulation coordinate system is given. For example, both ‘upper-right-domain’ and [‘upper’, ‘right’, ‘domain’] place the origin in the upper right hand corner of domain space. If x or y are not given, a value is inferred. For instance, ‘left-domain’ corresponds to the lower-left hand corner of the simulation domain, ‘center-domain’ corresponds to the center of the simulation domain, or ‘center-window’ for the center of the plot window. In the event that none of these options place the origin in a desired location, a sequence of tuples and a string specifying the coordinate space can be given. If plain numeric types are input, units of code_length are assumed. Further examples:
format
example
’{space}’
’domain’
’{xloc}-{space}’
’left-window’
’{yloc}-{space}’
’upper-domain’
’{yloc}-{xloc}-{space}’
’lower-right-window’
(‘{space}’,)
(‘window’,)
(‘{xloc}’, ‘{space}’)
(‘right’, ‘domain’)
(‘{yloc}’, ‘{space}’)
(‘lower’, ‘window’)
(‘{yloc}’, ‘{xloc}’, ‘{space}’)
(‘lower’, ‘right’, ‘window’)
((yloc, ‘{unit}’), (xloc, ‘{unit}’), ‘{space}’)
((0, ‘m’), (.4, ‘m’), ‘window’)
(xloc, yloc, ‘{space}’)
(0.23, 0.5, ‘domain’)
axes_unit (string) – The name of the unit for the tick labels on the x and y axes. Defaults to None, which automatically picks an appropriate unit. If axes_unit is ‘1’, ‘u’, or ‘unitary’, it will not display the units, and only show the axes name.
fontsize (integer) – The size of the fonts for the axis, colorbar, and tick labels.
field_parameters (dictionary) – A dictionary of field parameters than can be accessed by derived fields.
data_source (YTSelectionContainer object) – Object to be used for data selection. Defaults to ds.all_data(), a region covering the full domain