yt.visualization.particle_plots module

class yt.visualization.particle_plots.ParticleAxisAlignedDummyDataSource(center, ds, axis, width, fields, weight_field=None, field_parameters=None, data_source=None, deposition='ngp', density=False)[source]

Bases: object

get_field_parameter(name, default=None)[source]

This is typically only used by derived field functions, but it returns parameters used to generate fields.

class yt.visualization.particle_plots.ParticlePhasePlot(data_source, x_field, y_field, z_fields=None, color='b', x_bins=800, y_bins=800, weight_field=None, deposition='ngp', fontsize=18, figure_size=8.0, shading='nearest')[source]

Bases: yt.visualization.profile_plotter.PhasePlot

Create a 2d particle phase plot from a data source or from a yt.data_objects.profiles.ParticleProfile object.

Given a data object (all_data, region, sphere, etc.), an x field, y field, and z field (or fields), this will create a particle plot by depositing the particles onto a two-dimensional mesh, using either nearest grid point or cloud-in-cell deposition.

Parameters
  • data_source (YTSelectionContainer Object) – The data object to be profiled, such as all_data, region, or sphere.

  • x_field (str) – The x field for the mesh.

  • y_field (str) – The y field for the mesh.

  • z_fields (None, str, or list) – If None, particles will be splatted onto the mesh, but no colormap will be used. If str or list, the name of the field or fields to be displayed on the colorbar. The displayed values will correspond to the sum of the field or fields along the line of sight. Default: None.

  • color ('b', 'g', 'r', 'c', 'm', 'y', 'k', or 'w') – One the matplotlib-recognized color strings. The color that will indicate the particle locations on the mesh. This argument is ignored if z_fields is not None. Default : ‘b’

  • x_bins (int) – The number of bins in x field for the mesh. Default: 800.

  • y_bins (int) – The number of bins in y field for the mesh. Default: 800.

  • weight_field (str) – The field to weight by. If given, the plot will show a weighted average along the line of sight of the fields given in the z_fields argument. Default: None.

  • deposition (str) – Either ‘ngp’ or ‘cic’. Controls what type of interpolation will be used to deposit the particle z_fields onto the mesh. Default: ‘ngp’

  • fontsize (int) – Font size for all text in the plot. Default: 18.

  • figure_size (int) – Size in inches of the image. Default: 8 (8x8)

  • shading (str) – This argument is directly passed down to matplotlib.axes.Axes.pcolormesh see https://matplotlib.org/3.3.1/gallery/images_contours_and_fields/pcolormesh_grids.html#sphx-glr-gallery-images-contours-and-fields-pcolormesh-grids-py # noqa Default: ‘nearest’

Examples

>>> import yt
>>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030")
>>> ad = ds.all_data()
>>> plot = ParticlePhasePlot(
...     ad,
...     "particle_position_x",
...     "particle_position_y",
...     ["particle_mass"],
...     x_bins=800,
...     y_bins=800,
... )
>>> plot.save()
>>> # Change plot properties.
>>> plot.set_log("particle_mass", True)
>>> plot.set_unit("particle_position_x", "Mpc")
>>> plot.set_unit("particle_velocity_z", "km/s")
>>> plot.set_unit("particle_mass", "Msun")
annotate_text(xpos=0.0, ypos=0.0, text=None, **text_kwargs)

Allow the user to insert text onto the plot The x-position and y-position must be given as well as the text string. Add text tp plot at location xpos, ypos in plot coordinates (see example below).

Parameters
  • xpos (float) – Position on plot in x-coordinates.

  • ypos (float) – Position on plot in y-coordinates.

  • text (str) – The text to insert onto the plot.

  • **text_kwargs (dict) – Extra keyword arguments will be passed to matplotlib text instance

  • plot.annotate_text(1e-15, 5e4, "Hello YT") (>>>) –

annotate_title(title)

Set a title for the plot.

Parameters

title (str) – The title to add.

Examples

>>> plot.annotate_title("This is a phase plot")
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 fields
classmethod from_profile(profile, fontsize=18, figure_size=8.0, shading='nearest')

Instantiate a PhasePlot object from a profile object created with create_profile().

Parameters

Examples

>>> import yt
>>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030")
>>> extrema = {
...     ("gas", "density"): (1e-31, 1e-24),
...     ("gas", "temperature"): (1e1, 1e8),
...     ("gas", "mass"): (1e-6, 1e-1),
... }
>>> profile = yt.create_profile(
...     ds.all_data(),
...     [("gas", "density"), ("gas", "temperature")],
...     fields=[("gas", "mass")],
...     extrema=extrema,
...     fractional=True,
... )
>>> ph = yt.PhasePlot.from_profile(profile)
>>> ph.save()
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=False)

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 to True.

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()
plot_title = None
property profile
refresh()
reset_plot()
save(name=None, suffix='.png', mpl_kwargs=None)

Saves a 2d profile plot.

Parameters
  • name (str) – The output file keyword.

  • suffix (string) – 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) – A dict of keyword arguments to be passed to matplotlib.

  • plot.save(mpl_kwargs={"bbox_inches" (>>>) –

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_cbar_minorticks(field, state)

turn colorbar minor ticks “on” or “off” in the current plot, following state

Parameters
  • field (string) – the field to remove colorbar minorticks

  • state (string) – the state indicating ‘on’ or ‘off’

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.

Parameters
  • field (str or tuple) – The name of the field to modify the label for.

  • label (str) – The new label

  • plot.set_colorbar_label( (>>>) –

  • ("gas", "density"), "Dark Matter Density (g cm$^{-3}$)" (..) –

  • ) (..) –

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) – The size of the figure on the longest axis (in units of inches), including the margins but not the colorbar.

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.

>>> prof = ProfilePlot(
...     ds.all_data(), ("gas", "density"), ("gas", "temperature")
... )
>>> 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) –

  • absolute size of the font in points (1 pt = 1/72 inch) (The) –

set_log(field, log)

set a field to log or linear.

Parameters
  • field (string) – the field to set a transform

  • log (boolean) – Log on/off.

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_title(field, title)

Set a title for the plot.

Parameters
  • field (str) – The z field of the plot to add the title.

  • title (str) – The title to add.

Examples

>>> plot.set_title(("gas", "mass"), "This is a phase plot")
set_transform(field, name)
set_unit(field, unit)

Sets a new unit for the requested field

Parameters
  • field (string) – The name of the field that is to be changed.

  • unit (string or Unit object) – The name of the new unit.

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.

  • plot.set_xlabel("H2I Number Density (cm$^{-3}$)") (>>>) –

set_xlim(xmin=None, xmax=None)

Sets the limits of the x bin field

Parameters
  • xmin (float or None) – The new x minimum in the current x-axis units. Defaults to None, which leaves the xmin unchanged.

  • xmax (float or None) – The new x maximum in the current x-axis units. Defaults to None, which leaves the xmax unchanged.

Examples

>>> import yt
>>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030")
>>> pp = yt.PhasePlot(ds.all_data(), "density", "temperature", ("gas", "mass"))
>>> pp.set_xlim(1e-29, 1e-24)
>>> pp.save()
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.

  • plot.set_ylabel("Temperature (K)") (>>>) –

set_ylim(ymin=None, ymax=None)

Sets the plot limits for the y bin field.

Parameters
  • ymin (float or None) – The new y minimum in the current y-axis units. Defaults to None, which leaves the ymin unchanged.

  • ymax (float or None) – The new y maximum in the current y-axis units. Defaults to None, which leaves the ymax unchanged.

Examples

>>> import yt
>>> ds = yt.load("IsolatedGalaxy/galaxy0030/galaxy0030")
>>> pp = yt.PhasePlot(
...     ds.all_data(),
...     ("gas", "density"),
...     ("gas", "temperature"),
...     ("gas", "mass"),
... )
>>> pp.set_ylim(1e4, 1e6)
>>> pp.save()
set_zlim(field, zmin, zmax, dynamic_range=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, tuple, YTQuantity or str) – the new minimum of the colormap scale. If ‘min’, will set to the minimum value in the current view.

  • zmax (float, tuple, YTQuantity or str) – the new maximum of the colormap scale. If ‘max’, will set to the maximum value in the current view.

Other Parameters

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 When dynamic_range is specified, defaults to setting zmin = zmax / dynamic_range.

setup_defaults()
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.mods 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)) –

  • name of the field(s) that we want to show the colorbar. (The) –

x_log = None
y_log = None
yt.visualization.particle_plots.ParticlePlot(ds, x_field, y_field, z_fields=None, color='b', *args, **kwargs)[source]

A factory function for yt.visualization.particle_plots.ParticleProjectionPlot and yt.visualization.profile_plotter.ParticlePhasePlot objects. This essentially allows for a single entry point to both types of particle plots, the distinction being determined by the fields passed in.

If the x_field and y_field combination corresponds to a valid, right-handed spatial plot, an ParticleProjectionPlot will be returned. This plot object can be updated using one of the many helper functions defined in PlotWindow.

If the x_field and y_field combo do not correspond to a valid ParticleProjectionPlot, then a ParticlePhasePlot. This object can be modified by its own set of helper functions defined in PhasePlot. We note below which arguments are only accepted by ParticleProjectionPlot and which arguments are only accepted by ParticlePhasePlot.

Parameters
  • ds (yt.data_objects.static_output.Dataset) – This is the dataset object corresponding to the simulation output to be plotted.

  • x_field (string) – This is the particle field that will be plotted on the x-axis.

  • y_field (string) – This is the particle field that will be plotted on the y-axis.

  • z_fields (string, list, or None.) – If None, particles will be splatted onto the plot, but no colormap will be used. The particle color will instead be determined by the ‘color’ argument. If str or list, the name of the field or fields to be displayed on the colorbar. Default: None.

  • color ('b', 'g', 'r', 'c', 'm', 'y', 'k', or 'w') – One the matplotlib-recognized color strings. The color that will indicate the particle locations on the plot. This argument is ignored if z_fields is not None. Default is ‘b’.

  • weight_field (string) – The name of the weighting field. Set to None for no weight.

  • fontsize (integer) – The size of the fonts for the axis, colorbar, and tick labels.

  • data_source (YTSelectionContainer Object) – Object to be used for data selection. Defaults to a region covering the entire simulation.

  • center (A sequence of floats, a string, or a tuple.) – The coordinate of the center of the image. If set to ‘c’, ‘center’ or left blank, the plot is centered on the middle of the domain. If set to ‘max’ or ‘m’, the center will be located at the maximum of the (‘gas’, ‘density’) field. Centering on the max or min of a specific field is supported by providing a tuple such as (“min”,”temperature”) or (“max”,”dark_matter_density”). Units can be specified by passing in center as a tuple containing a coordinate and string unit name or by passing in a YTArray. If a list or unitless array is supplied, code units are assumed. This argument is only accepted by ParticleProjectionPlot.

  • 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. This argument is only accepted by ParticleProjectionPlot.

  • 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. Defaults to the entire domain. This argument is only accepted by ParticleProjectionPlot.

  • axes_unit (A 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 of strings) –

    The location of the origin of the plot coordinate system. This is represented by ‘-‘ 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’] both 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. 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’)

    This argument is only accepted by ParticleProjectionPlot.

  • window_size (float) – The size of the window on the longest axis (in units of inches), including the margins but not the colorbar. This argument is only accepted by ParticleProjectionPlot.

  • aspect (float) – The aspect ratio of the plot. Set to None for 1. This argument is only accepted by ParticleProjectionPlot.

  • x_bins (int) – The number of bins in x field for the mesh. Defaults to 800. This argument is only accepted by ParticlePhasePlot.

  • y_bins (int) – The number of bins in y field for the mesh. Defaults to 800. This argument is only accepted by ParticlePhasePlot.

  • deposition (str) – Either ‘ngp’ or ‘cic’. Controls what type of interpolation will be used to deposit the particle z_fields onto the mesh. Defaults to ‘ngp’.

  • figure_size (int) – Size in inches of the image. Defaults to 8 (product an 8x8 inch figure). This argument is only accepted by ParticlePhasePlot.

Examples

>>> from yt import load
>>> ds = load("IsolatedGalaxy/galaxy0030/galaxy0030")
>>> p = yt.ParticlePlot(
...     ds,
...     "particle_position_x",
...     "particle_position_y",
...     "particle_mass",
...     width=(0.5, 0.5),
... )
>>> p.set_unit("particle_mass", "Msun")
>>> p = yt.ParticlePlot(ds, "particle_position_x", "particle_velocity_z", color="g")
class yt.visualization.particle_plots.ParticleProjectionPlot(ds, axis, fields=None, color='b', center='c', width=None, depth=1, '1', weight_field=None, axes_unit=None, origin='center-window', fontsize=18, field_parameters=None, window_size=8.0, aspect=None, data_source=None, deposition='ngp', density=False)[source]

Bases: yt.visualization.plot_window.PWViewerMPL

Creates a particle 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.

  • axis (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, list or None) – If a string or list, the name of the particle field(s) to be used on the colorbar. The color shown will correspond to the sum of the given field along the line of sight. If None, the particle positions will be indicated using a fixed color, instead. Default is None.

  • color ('b', 'g', 'r', 'c', 'm', 'y', 'k', or 'w') – One the matplotlib-recognized color strings. The color that will indicate the particle locations on the mesh. This argument is ignored if z_fields is not None. Default is ‘b’.

  • center (A sequence of floats, a string, or a tuple.) – The coordinate of the center of the image. If set to ‘c’, ‘center’ or left blank, the plot is centered on the middle of the domain. If set to ‘max’ or ‘m’, the center will be located at the maximum of the (‘gas’, ‘density’) field. Centering on the max or min of a specific field is supported by providing a tuple such as (“min”,”temperature”) or (“max”,”dark_matter_density”). Units can be specified by passing in center as a tuple containing a coordinate and string unit name or by passing in a YTArray. If a list or unitless array is supplied, code units are assumed.

  • 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. Defaults to the entire domain.

  • weight_field (string) – The name of the weighting field. Set to None for no weight. If given, the plot will show a weighted average along the line of sight of the fields given in the fields argument.

  • axes_unit (A 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 of strings) –

    The location of the origin of the plot coordinate system. This is represented by ‘-‘ 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’] both 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. 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’)

  • 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.

  • window_size (float) – The size of the window on the longest axis (in units of inches), including the margins but not the colorbar.

  • aspect (float) – The aspect ratio of the plot. Set to None for 1.

  • data_source (YTSelectionContainer Object) – Object to be used for data selection. Defaults to a region covering the entire simulation.

  • deposition (string) – Controls the order of the interpolation of the particles onto the mesh. “ngp” is 0th-order “nearest-grid-point” method (the default), “cic” is 1st-order “cloud-in-cell”.

  • density (boolean) – If True, the quantity to be projected will be divided by the area of the cells, to make a projected density of the quantity. The plot name and units will also reflect this. Default: False

Examples

This will save an image the the file ‘galaxy0030_Particle_z_particle_mass.png’

>>> from yt import load
>>> ds = load("IsolatedGalaxy/galaxy0030/galaxy0030")
>>> p = yt.ParticleProjectionPlot(ds, 2, "particle_mass")
>>> p.save()
annotate_clear(index=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.)

Note

Deprecated in favor of clear_annotations.

property bounds
clear_annotations(index=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%”)

Returns

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")
property frb

The frb property.

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=False)

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 to True.

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()
run_callbacks()
save(name=None, suffix='.png', mpl_kwargs=None)

saves the plot to disk.

Parameters
  • name (string or tuple) – 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) – 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) – 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_cbar_minorticks(field, state)

turn colorbar minor ticks “on” or “off” in the current plot, following state

Parameters
  • field (string) – the field to remove colorbar minorticks

  • state (string) – the state indicating ‘on’ or ‘off’

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.

Parameters
  • field (str or tuple) – The name of the field to modify the label for.

  • label (str) – The new label

  • plot.set_colorbar_label( (>>>) –

  • ("gas", "density"), "Dark Matter Density (g cm$^{-3}$)" (..) –

  • ) (..) –

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) – The size of the figure on the longest axis (in units of inches), including the margins but not the colorbar.

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) –

  • absolute size of the font in points (1 pt = 1/72 inch) (The) –

set_log(field, log, linthresh=None, symlog_auto=False)

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 alue for linthresh.

Parameters
  • field (string) – the field to set a transform if field == ‘all’, applies to all plots.

  • log (boolean) – Log on/off: on means log scaling; off means linear scaling. Unless a linthresh is set or symlog_auto is set in which case symlog is used.

  • linthresh (float, 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

  • symlog_auto (boolean) – if symlog_auto is True, then yt will use symlog scaling and attempt to determine a linthresh automatically. Setting a linthresh manually overrides this value.

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, _setup_plots() 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._setup_plots()
>>> 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._setup_plots()
>>> 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._setup_plots()
>>> 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._setup_plots()
>>> p.plots["AIRDENS"].axes.set_global()
>>> p.plots["AIRDENS"].axes.coastlines()
>>> p.show()
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}') –

  • ('window',) (('{space}',)) –

  • '{space}') ('right', 'domain') (('{xloc}',) –

  • '{space}') ('lower', 'window') (('{yloc}',) –

  • '{xloc}', '{space}') ('lower', 'right', 'window') (('{yloc}',) –

  • '{unit}'), (xloc, '{unit}'), '{space}') ((0, 'm'), (4, 'm'), 'window') (((yloc,) –

  • yloc, '{space}') (0.23, 0.5, 'domain') ((xloc,) –

  • ===============================

set_transform(field, name)
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) – The name of the new unit.

  • 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_window_size(size)

This calls set_figure_size to adjust the size of the plot window.

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.

  • plot.set_xlabel("H2I Number Density (cm$^{-3}$)") (>>>) –

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.

  • plot.set_ylabel("Temperature (K)") (>>>) –

set_zlim(field, zmin, zmax, dynamic_range=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, tuple, YTQuantity or str) – the new minimum of the colormap scale. If ‘min’, will set to the minimum value in the current view.

  • zmax (float, tuple, YTQuantity or str) – the new maximum of the colormap scale. If ‘max’, will set to the maximum value in the current view.

Other Parameters

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 When dynamic_range is specified, defaults to setting zmin = zmax / dynamic_range.

setup_callbacks()
setup_defaults()
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.mods 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)) –

  • name of the field(s) that we want to show the colorbar. (The) –

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.

toggle_right_handed()
property width
zoom(factor)

This zooms the window by factor > 0. - zoom out with factor < 1 - zoom in with factor > 1

Parameters

factor (float) – multiplier for the current width