Plotting Tools: Display models and data

The plot module provides mechanisms for plotting models, observations, and model fits.

The ModelPlot class can be used plotting models and observations without any \(\chi^2\) fitting. An example notebook for using ModelPlot is PDRT_Example_ModelPlotting.ipynb .

Some classes are paired with analysis tools in the tool module. LineRatioPlot which is used to plot the results of LineRatioFit, and H2ExcitationPlot that is used in H2Excitation. All plot classes are derived from PlotBase.

Plot Keywords

To manage the plots, the methods in Plot classes take keywords (**kwargs) that turn on or off various options, specify plot units, or map to matplotlib’s plot(), imshow(), contour() keywords. The methods have reasonable defaults, so try them with no keywords to see what they do before modifying keywords.

  • units (str or astropy.units.Unit) image data units to use in the plot. This can be either a string such as, ‘cm^-3’ or ‘Habing’, or it can be an astropy.units.Unit. Data will be converted to the desired unit. Note these are not the axis units, but the image data units. Modifying axis units is implemented via the xaxis_unit and yaxis_unit keywords.

  • image (bool) whether or not to display the image map (imshow).

  • show (str) which quantity to display in the Measurement, one of ‘data’, ‘error’, ‘mask’. For example, this can be used to plot the errors in observed ratios. Default: ‘data’

  • cmap (str) colormap name, Default: ‘plasma’

  • colorbar (str) whether or not to display colorbar

  • colors (str) color of the contours. Default: ‘whitecolor of the contours. Default: ‘white’

  • contours (bool), whether or not to plot contours

  • label (bool), whether or not to label contours

  • linewidths (float or sequence of float), the line width in points, Default: 1.0

  • legend (bool) Draw a legend on the plot. If False, a title is drawn above the plot with the value of the title keyword

  • bbox_to_anchor (tuple) The matplotlib legend keyword for controlling the placement of the legend. See the matplotlib Legend Guide

  • loc (str) The matplotlib legend keyword for controlling the location of the legend. See legend().

  • levels (int or array-like) Determines the number and positions of the contour lines / regions. If an int n, use n data intervals; i.e. draw n+1 contour lines. The level heights are automatically chosen. If array-like, draw contour lines at the specified levels. The values must be in increasing order.

  • measurements (array-like) A list of single pixel Measurements that can be contoured over a model ratio or intensity map.

  • meas_color (array of str) A list of colors to use when overlaying Measurement contours. There should be one color for each Measurement in the measurement keyword. The Default of None will use a color-blind friendly color cycle.

  • norm (str or astropy.visualization normalization object) The normalization to use in the image. The string ‘simple’ will normalize with simple_norm() and ‘zscale’ will normalize with IRAF’s zscale algorithm. See ZScaleInterval.

  • stretch (str) {‘linear’, ‘sqrt’, ‘power’, ‘log’, ‘asinh’}. The stretch function to apply to the image for simple_norm. The Default is ‘linear’.

  • aspect (str) aspect ratio, ‘equal’ or ‘auto’ are typical defaults.

  • origin (str) Origin of the image. Default: ‘lower’

  • title (str) A title for the plot. LaTeX allowed.

  • vmin (float) Minimum value for colormap normalization

  • vmax (float) Maximum value for colormap normalization

  • xaxis_unit (str or astropy.units.Unit) X axis (density) units to use when plotting models, such as in overlay_all_ratios() or modelratio(). If None, the native model axis units are used.

  • yaxis_unit (str or astropy.units.Unit) Y axis (density) units to use when plotting models, such as in overlay_all_ratios() or modelratio(). If None, the native model axis units are used.

The following keywords are available, but you probably won’t touch.

  • nrows (int) Number of rows in the subplot

  • ncols (int) Number of columns in the subplot

  • index (int) Index of the subplot

  • reset (bool) Whether or not to reset the figure.

Providing keywords other than these has undefined results, but may just work!


PlotBase

class pdrtpy.plot.plotbase.PlotBase(tool)[source]

Bases: object

Base class for plotting.

Parameters:

tool (Any class derived from ToolBase) – Reference to a tool object or None. This is used for classes that inherit from PlotBase and are coupled to a specific tool, e.g. LineRatioPlot and LineRatioFit.

Attributes:
axis

The last axis that was drawn.

figure

The last figure that was drawn.

Methods

colorcycle(colorcycle)

Set the plot color cycle for multi-trace plots.

reset_colorcycle()

Reset the color cycle to the default color-blind friendly one

savefig(fname, **kwargs)

Save the current figure to a file.

text(x, y, s[, fontdict])

Add text to the Axes.

usetex(use)

Control whether plots delegate rendering of fancy text components in axis labels and elsewhere to the system version of LaTeX or use matplotlib's rendering.

property axis

The last axis that was drawn.

Return type:

matplotlib.axes._subplots.AxesSubplot

colorcycle(colorcycle)[source]

Set the plot color cycle for multi-trace plots. The default color cycle is optimized for color-blind users.

Parameters:

colorcycle (list) – List of colors to use, typically a list of hex color strings. This list will be passed to matplotlib.pyplot.rc() as the axes prop_cycle parameter using matplotlib.cycler.

property figure

The last figure that was drawn.

Return type:

matplotlib.figure.Figure

reset_colorcycle()[source]

Reset the color cycle to the default color-blind friendly one

savefig(fname, **kwargs)[source]

Save the current figure to a file.

Parameters:

fname (str) – filename to save in

Keyword Arguments:

Additional arguments (**kwargs) are passed to matplotlib.pyplot.savefig(). e.g. bbox_inches=’tight’ for a tight layout.

text(x, y, s, fontdict=None, **kwargs)[source]

Add text to the Axes. Add the text s to the Axes at location x, y in data coordinates. This calls through to matplotlib.pyplot.text().

Parameters:
  • x (float) – the horizontal coordinate for the text

  • y (float) – the vertical coordinate for the text

  • s (str) – the text

  • fontdict (dict) – A dictionary to override the default text properties. If fontdict is None, the defaults are determined by rcParams.

  • **kwargs – Other miscellaneous Text parameters.

usetex(use)[source]

Control whether plots delegate rendering of fancy text components in axis labels and elsewhere to the system version of LaTeX or use matplotlib’s rendering. This method sets matplotlib parameter rcParams[“text.usetex”] in the local pyplot instance. Note: You must have LaTeX installed on your system if setting this to True or an exception will be raised when you try to plot.

Parameters:

use (bool) – whether to use LaTeX or not

ExcitationPlot

class pdrtpy.plot.excitationplot.ExcitationPlot(tool, label)[source]

Bases: PlotBase

ExcitationPlot creates excitation diagrams using the results of H2ExcitationFit. It can plot the observed excitation diagram with or without fit results, and allows averaging over user-given spatial areas.

Attributes:
axis

The last axis that was drawn.

figure

The last figure that was drawn.

Methods

colorcycle(colorcycle)

Set the plot color cycle for multi-trace plots.

column_density(component[, log])

Plot the column density of hot or cold gas component, or total column density.

ex_diagram([position, size, norm, show_fit])

Plot the excitation diagram.

explore([data, interaction_type])

Explore the fitted parameters of a map.

opr(**kwargs)

Plot the ortho-to-para ratio.

reset_colorcycle()

Reset the color cycle to the default color-blind friendly one

savefig(fname, **kwargs)

Save the current figure to a file.

temperature(component, **kwargs)

Plot the temperature of hot or cold gas component.

text(x, y, s[, fontdict])

Add text to the Axes.

usetex(use)

Control whether plots delegate rendering of fancy text components in axis labels and elsewhere to the system version of LaTeX or use matplotlib's rendering.

column_density(component, log=True, **kwargs)[source]

Plot the column density of hot or cold gas component, or total column density.

Parameters:
  • component (str) – ‘hot’, ‘cold’, or ‘total

  • log – take the log10 of the column density before plotting

ex_diagram(position=None, size=None, norm=True, show_fit=False, **kwargs)[source]

Plot the excitation diagram. For maps of excitation parameters, a position and optional size are required. To examine the entire map, use explore().

Parameters:
  • position (tuple) – The spatial position of excitation diagram. For spatial averaging this is the cutout array’s center with respect to the data array. The position is specified as a (x, y) tuple of pixel coordinates.

  • size (int, array_like, or astropy.units.Quantity) – The size of the cutout array along each axis. If size is a scalar number or a scalar Quantity, then a square cutout of size will be created. If size has two elements, they should be in (ny, nx) order. Scalar numbers in size are assumed to be in units of pixels. size can also be a Quantity object or contain Quantity objects. Such Quantity objects must be in pixel or angular units. For all cases, size will be converted to an integer number of pixels, rounding the the nearest integer. See Cutout2D

  • norm (bool) – if True, normalize the column densities by the statistical weight of the upper state, \(g_u\).

  • show_fit (bool) – Show the most recent fit done the the associated H2ExcitationFit tool.

explore(data=None, interaction_type='click', **kwargs)[source]

Explore the fitted parameters of a map. A user-requested map is displayed in the left panel and in the right panel is the fitted excitation diagram for a point selected by the user. The user clicks on a point in the left panel and the right panel will update with the excitation diagram for that point.

Parameters:
  • data (Measurement) – A reference image to use for the left panel, e.g. the total column density, the cold temperature, etc. This should be a reference results in the H2Excitation tool used for this ExcitationPlot (e.g., htool.temperature[‘cold’])

  • interaction_type (str) – whether to use mouse click or mouse move to update the right hand panel. Valid values are ‘click’ or ‘move’.

  • **kwargs

    Other parameters passed to _plot(), ex_diagram(), or matplotlib methods.

    • units,image, contours, label, title, norm, figsize – See the general Plot Keywords documentation

    • show_fit - show the fit in the excitation diagram, Default: True

    • log - plot the log10 of the image, can be useful for column density, Default: False

    • markersize - size of the marker displayed where clicked, in points, Default: 20

    • fmt - matplotlib format for the marker, Default:. ‘r+’

opr(**kwargs)[source]

Plot the ortho-to-para ratio. This will be a map if the input data are a map, otherwise a float value is returned.

temperature(component, **kwargs)[source]

Plot the temperature of hot or cold gas component.

Parameters:

component (str) – ‘hot’ or ‘cold’

LineRatioPlot

class pdrtpy.plot.lineratioplot.LineRatioPlot(tool)[source]

Bases: PlotBase

LineRatioPlot plots the results of LineRatioFit. It can plot maps of fit results, observations with errors on top of models, chi-square and confidence intervals and more.

Keyword Arguments:

The methods of this class can take a variety of optional keywords. See the general Plot Keywords documentation

Attributes:
axis

The last axis that was drawn.

figure

The last figure that was drawn.

Methods

chisq(**kwargs)

Plot the \(\chi^2\) map that was computed by the LineRatioFit tool.

colorcycle(colorcycle)

Set the plot color cycle for multi-trace plots.

confidence_intervals(**kwargs)

Plot the confidence intervals from the \(\chi^2\) map computed by the LineRatioFit tool.

density(**kwargs)

Plot the hydrogen nucleus volume density map that was computed by LineRatioFit tool.

modelintensity(id, **kwargs)

Plot one of the model intensities

modelratio(id, **kwargs)

Plot one of the model ratios

observedratio(id, **kwargs)

Plot one of the observed ratios

overlay_all_ratios(**kwargs)

Overlay all the measured ratios and their errors on the \((n,F_{FUV})\) space.

radiation_field(**kwargs)

Plot the radiation field map that was computed by LineRatioFit tool.

ratios_on_models(**kwargs)

Overlay all the measured ratios and their errors on the individual models for those ratios.

reduced_chisq(**kwargs)

Plot the reduced \(\chi^2\) map that was computed by the LineRatioFit tool.

reset_colorcycle()

Reset the color cycle to the default color-blind friendly one

savefig(fname, **kwargs)

Save the current figure to a file.

show_both([units])

Plot both radiation field and volume density maps computed by the LineRatioFit tool in a 1x2 panel subplot.

text(x, y, s[, fontdict])

Add text to the Axes.

usetex(use)

Control whether plots delegate rendering of fancy text components in axis labels and elsewhere to the system version of LaTeX or use matplotlib's rendering.

chisq(**kwargs)[source]

Plot the \(\chi^2\) map that was computed by the LineRatioFit tool.

confidence_intervals(**kwargs)[source]

Plot the confidence intervals from the \(\chi^2\) map computed by the LineRatioFit tool. Default levels: [50., 68., 80., 95., 99.]

Currently only works for single-pixel Measurements

density(**kwargs)[source]

Plot the hydrogen nucleus volume density map that was computed by LineRatioFit tool. Default units: cm \(^{-3}\)

modelintensity(id, **kwargs)[source]

Plot one of the model intensities

Parameters:
  • id (str) – the intensity identifier, such as CO_32`.

  • **kwargs – see class documentation above

Raises:

KeyError – if is id not in existing model intensities

modelratio(id, **kwargs)[source]

Plot one of the model ratios

Parameters:
  • id (str) – the ratio identifier, such as CII_158/CO_32.

  • **kwargs – see class documentation above

Raises:

KeyError – if is id not in existing model ratios

observedratio(id, **kwargs)[source]

Plot one of the observed ratios

Parameters:

id – the ratio identifier, such as CII_158/CO_32.

Raises:

KeyError – if id is not in existing observed ratios

overlay_all_ratios(**kwargs)[source]

Overlay all the measured ratios and their errors on the \((n,F_{FUV})\) space.

This only works for single-valued Measurements; an overlay for multi-pixel doesn’t make sense.

radiation_field(**kwargs)[source]

Plot the radiation field map that was computed by LineRatioFit tool. Default units: Habing.

ratios_on_models(**kwargs)[source]

Overlay all the measured ratios and their errors on the individual models for those ratios. Plots are displayed in multi-column format, controlled the ncols keyword. Default: ncols=2

Currently only works for single-pixel Measurements

reduced_chisq(**kwargs)[source]

Plot the reduced \(\chi^2\) map that was computed by the LineRatioFit tool.

show_both(units=['Habing', 'cm^-3'], **kwargs)[source]

Plot both radiation field and volume density maps computed by the LineRatioFit tool in a 1x2 panel subplot. Default units: [‘Habing’,’cm^-3’]

ModelPlot

class pdrtpy.plot.modelplot.ModelPlot(modelset, figure=None, axis=None)[source]

Bases: PlotBase

ModelPlot is a tool for exploring sets of models. It can plot individual intensity or ratio models, phase-space diagrams, and optionally overlay observations. Units are seamlessly transformed, so you can plot in Habing units, Draine units, or any conformable quantity. ModelPlot does not require model fitting with LineRatioFit first.

Keyword Arguments:

The methods of this class can take a variety of optional keywords. See the general Plot Keywords documentation.

Attributes:
axis

The last axis that was drawn.

figure

The last figure that was drawn.

Methods

colorcycle(colorcycle)

Set the plot color cycle for multi-trace plots.

intensity(identifier, **kwargs)

Plot a model ratio

isoplot(identifier, plotnaxis[, nax_clip])

Plot lines of constant model parameter as a function of the other model parameter and a model intensity or ratio

overlay(measurements, **kwargs)

Overlay one or more single-pixel measurements in the model space \((n,F_{FUV})\).

phasespace(identifiers[, nax1_clip, ...])

Plot lines of constant density and radiation field on a ratio-ratio, ratio-intensity, or intensity-intensity map

plot(identifier, **kwargs)

Plot a model intensity or ratio

ratio(identifier, **kwargs)

Plot a model ratio

reset_colorcycle()

Reset the color cycle to the default color-blind friendly one

savefig(fname, **kwargs)

Save the current figure to a file.

text(x, y, s[, fontdict])

Add text to the Axes.

usetex(use)

Control whether plots delegate rendering of fancy text components in axis labels and elsewhere to the system version of LaTeX or use matplotlib's rendering.

intensity(identifier, **kwargs)[source]

Plot a model ratio

Parameters:

identifier (str) – Identifier tag for the model to plot, e.g., “OI_63”, “CII_158”, “CO_10”]

See also

supported_intensities() for a list of available identifer tags

isoplot(identifier, plotnaxis, nax_clip=<Quantity [  1000., 100000.] K>, **kwargs)[source]

Plot lines of constant model parameter as a function of the other model parameter and a model intensity or ratio

Parameters:
  • identifier (str) – identifier tag for the model to plot, e.g., “OI_63/CO_21” or “CII_158”

  • plotnaxis (int) – Which NAXIS to use to compute lines of constant value. Since models have two axes, this must be either 1 or 2

  • nax_clip (array-like, must contain Quantity) – The range of model parameters on NAXIS{plotnaxis} to show in the plot. Must be given as a range of astropy quanitities, e.g. [10,1E7]*Unit(“cm-3”). Default is None which means plot full range of the parameter.

  • step (int) – Allows skipping of lines of constant value, e.g. plot every step-th value. Useful when parameter space is crowded, and a cleaner looking plot is desired. Default: 1 – plot every value

overlay(measurements, **kwargs)[source]

Overlay one or more single-pixel measurements in the model space \((n,F_{FUV})\).

Parameters:
  • measurements (list) – a list of one or more Measurement to overlay.

  • shading (float) – Controls how measurements and errors are drawn. If shading is zero, Measurements will be drawn in solid contour for the value and dashed for the +/- errors. If shading is between 0 and 1, Measurements are drawn with as filled contours representing the size of the errors (see matplotlib.pyplot.contourf()) with alpha set to the shading value. Default value: 0.4

phasespace(identifiers, nax1_clip=<Quantity [1.e+01, 1.e+07] 1 / cm3>, nax2_clip=<Quantity [1.e+01, 1.e+06] Habing>, reciprocal=[False, False], **kwargs)[source]

Plot lines of constant density and radiation field on a ratio-ratio, ratio-intensity, or intensity-intensity map

Parameters:
  • identifiers (list of str) – list of two identifier tags for the model to plot, e.g., [“OI_63/CO_21”, “CII_158”]

  • nax1_clip (array-like, must contain Quantity) – The range of model densities on NAXIS1 to show in the plot. For most model NAXIS1 is hydrogen number density $n_H$ in cm$^{-3}$. For ionized gas models, it is electron temperature $T_e$ in K. Must be given as a range of astropy quanitities. Default: [10,1E7]*Unit(“cm-3”)

  • nax2_clip (array-like, must contain Quantity) – The range of model parameters on NAXIS2 to show in the plot. For most models NAXIS2 is radiation field intensities in Habing or cgs units. For ionized gas models, it is electron volume density $n_e$. Must be given as a range of astropy quantities. Default: nax1_clip=[10,1E6]*utils.habing_unit.

  • reciprocal (array-like bool) – Whether or not the plot the reciprocal of the model on each axis. Given as a pair of booleans. e.g. [False,True] means don’t flip the quantity X axis, but flip quantity the Y axis. i.e. if the model is “CII/OI”, and reciprocal=True then the axis will be “OI/CII”. Default: [False, False]

The following keywords are supported as **kwargs:

Parameters:
  • measurements (array-like of Measurement.) – A list of two Measurement, one for each identifier, that will be used to plot a data point on the grid. At least two Measurements, one for x and one for y, must be given. Subsequent Measurements must also be paired since they represent x and y, e.g [m1x, m1y, m2x, m2y,…]. Measurement data and uncertainty members may be arrays. Default: None

  • errorbar (bool) – Plot error bars when given measurements. Default: True

  • fmt (array of str) – The format to use when plotting Measurement data. There should be one for each pair of Measurements. See matplotlib.axes.Axes.plot() for examples. Default is ‘sk’ for all points.

  • label (array of str) – The label(s) to use the Measurement data legend. There should be one for each pair of Measurements. Default is ‘data’ for all points.

  • legend (bool) – Draw a legend on the plot. Default: True

  • title (str) – Title to draw on the plot. Default: None

  • linewidth (float) – line width

  • grid (bool) – show grid or not, Default: True

  • figsize (2-tuple of floats) – Figure dimensions (width, height) in inches. Default: (8,5)

  • capsize (float) – end cap length of errorbars if shown, in points. Default: 3.

  • markersize (float) – size of data point marker in points. Default: 8

plot(identifier, **kwargs)[source]

Plot a model intensity or ratio

Parameters:

identifier (str) – Identifier tag for the model to plot, e.g., “CII_158”,”OI_145”,”CO_43/CO_21’]

See also

supported_lines() for a list of available identifer tags

ratio(identifier, **kwargs)[source]

Plot a model ratio

Parameters:

identifier (str) – Identifier tag for the model to plot, e.g., “OI_63+CII_158/FIR”, “CO_43/CO_21’]

See also

supported_ratios() for a list of available identifer tags