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 ExcitationPlot that is used in H2ExcitationFit, COExcitationFit, and other molecular excitation fit classes. 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:
toolany 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 at location x, y in data coordinates.

usetex(use)

Control whether plots delegate rendering to the system LaTeX or use matplotlib's rendering.

property axis#

The last axis that was drawn.

Returns:
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:
colorcyclelist

List of colors to use, typically hex color strings. Passed to matplotlib.pyplot.rc() as the axes prop_cycle parameter using matplotlib.cycler.

property figure#

The last figure that was drawn.

Returns:
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:
fnamestr

Filename to save to.

**kwargs

Additional arguments 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 at location x, y in data coordinates.

Calls through to matplotlib.pyplot.text().

Parameters:
xfloat

The horizontal coordinate for the text.

yfloat

The vertical coordinate for the text.

sstr

The text.

fontdictdict, optional

A dictionary to override the default text properties. If None, the defaults are determined by rcParams.

**kwargs

Other miscellaneous Text parameters.

usetex(use)[source]#

Control whether plots delegate rendering to the system LaTeX or use matplotlib’s rendering.

Sets matplotlib parameter rcParams["text.usetex"] in the local pyplot instance. Note: You must have LaTeX installed if setting this to True or an exception will be raised when you try to plot.

Parameters:
usebool

Whether to use LaTeX or not.

ExcitationPlot#

class pdrtpy.plot.excitationplot.ExcitationPlot(tool, label=None)[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 interactively.

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 at location x, y in data coordinates.

usetex(use)

Control whether plots delegate rendering to the system 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:
componentstr

'hot', 'cold', or 'total'.

logbool, optional

Take the log10 of the column density before plotting. Default: True.

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:
positiontuple or SkyCoord, optional

The spatial position of the excitation diagram. For spatial averaging this is the cutout array’s center. May be an (x, y) tuple of pixel coordinates or a SkyCoord.

sizeint, array_like, or Quantity, optional

The size of the cutout array along each axis. If scalar, a square cutout is created. If two elements, they should be in (ny, nx) order. Scalar numbers are assumed to be in pixels. Quantity objects must be in pixel or angular units. See Cutout2D.

normbool, optional

If True, normalize the column densities by the statistical weight of the upper state \(g_u\). Default: True.

show_fitbool, optional

Show the most recent fit from the associated excitation fit tool. Default: False.

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

Explore the fitted parameters of a map interactively.

A user-requested map is displayed in the left panel; the right panel shows the fitted excitation diagram for a user-selected point.

Parameters:
dataMeasurement, optional

Reference image for the left panel, e.g. total column density or cold temperature from the associated excitation tool (e.g. htool.temperature['cold']).

interaction_typestr, optional

Whether to update the right panel on mouse 'click' or 'move'. Default: 'click'.

**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. 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:
componentstr

'hot' or 'cold'.

LineRatioPlot#

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

Bases: PlotBase

Plots the results of LineRatioFit.

Can plot maps of fit results, observations with errors on top of models, chi-square and confidence intervals and more.

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 at location x, y in data coordinates.

usetex(use)

Control whether plots delegate rendering to the system LaTeX or use matplotlib's rendering.

Parameters:
toolLineRatioFit

The line ratio fitting tool that is to be plotted.

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 at location x, y in data coordinates.

usetex(use)

Control whether plots delegate rendering to the system 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:
idstr

The intensity identifier, such as CO_32.

**kwargs

See class documentation above.

Raises:
KeyError

If id is not in existing model intensities.

modelratio(id, **kwargs)[source]#

Plot one of the model ratios.

Parameters:
idstr

The ratio identifier, such as CII_158/CO_32.

**kwargs

See class documentation above.

Raises:
KeyError

If id is not in existing model ratios.

observedratio(id, **kwargs)[source]#

Plot one of the observed ratios.

Parameters:
idstr

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=None, **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

Tool for exploring sets of models.

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.

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

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 at location x, y in data coordinates.

usetex(use)

Control whether plots delegate rendering to the system LaTeX or use matplotlib's rendering.

Parameters:
modelsetModelSet

The set of models to use in these plots.

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

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 at location x, y in data coordinates.

usetex(use)

Control whether plots delegate rendering to the system LaTeX or use matplotlib's rendering.

intensity(identifier, **kwargs)[source]#

Plot a model intensity.

Parameters:
identifierstr

Identifier tag for the model to plot, e.g., "OI_63", "CII_158", "CO_10".

See also

supported_intensities()

for a list of available identifier tags.

isoplot(identifier, plotnaxis, nax_clip=None, **kwargs)[source]#

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

Parameters:
identifierstr

Identifier tag for the model to plot, e.g., "OI_63/CO_21" or "CII_158".

plotnaxisint

Which NAXIS to use to compute lines of constant value. Since models have two axes, this must be either 1 or 2.

nax_cliparray-like of Quantity, optional

The range of model parameters on NAXIS{plotnaxis} to show. e.g. [10, 1E7]*Unit("cm-3"). Default: None (full range).

stepint, optional

Allows skipping lines of constant value, e.g. plot every step-th value. Useful when parameter space is crowded. Default: 1.

overlay(measurements, **kwargs)[source]#

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

Parameters:
measurementslist of Measurement

A list of one or more Measurements to overlay.

shadingfloat, optional

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

phasespace(identifiers, nax1_clip=None, nax2_clip=None, reciprocal=None, **kwargs)[source]#

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

Parameters:
identifierslist of str

List of two identifier tags for the model to plot, e.g., ["OI_63/CO_21", "CII_158"].

nax1_cliparray-like of Quantity, optional

Range of model densities on NAXIS1 to show. For most models, NAXIS1 is hydrogen number density \(n_H\) in \({\rm cm}^{-3}\). For ionized gas models, it is electron temperature \(T_e\) in K. Default: [10, 1E7]*Unit("cm-3").

nax2_cliparray-like of Quantity, optional

Range of model parameters on NAXIS2. For most models, NAXIS2 is radiation field intensities in Habing or cgs units. For ionized gas models, it is electron volume density \(n_e\). Default: [10, 1E6]*utils.habing_unit.

reciprocalarray-like of bool, optional

Whether to plot the reciprocal of the model on each axis. e.g. [False, True] means don’t flip the X axis but flip the Y axis. Default: [False, False].

measurementsarray-like of Measurement, optional

A list of two Measurements, one per identifier, to plot as data points on the grid. Pairs must be given as [m1x, m1y, m2x, m2y, ...]. Default: None.

errorbarbool, optional

Plot error bars when given measurements. Default: True.

fmtarray of str, optional

Plot format for each Measurement pair. See matplotlib.axes.Axes.plot(). Default: 'sk' for all points.

labelarray of str, optional

Legend label(s) for each Measurement pair. Default: 'data' for all.

legendbool, optional

Draw a legend on the plot. Default: True.

titlestr, optional

Title to draw on the plot. Default: None.

linewidthfloat, optional

Line width.

gridbool, optional

Show grid. Default: True.

figsize2-tuple of float, optional

Figure dimensions (width, height) in inches. Default: (8, 5).

capsizefloat, optional

End cap length of errorbars in points. Default: 3.

markersizefloat, optional

Size of data point marker in points. Default: 8.

plot(identifier, **kwargs)[source]#

Plot a model intensity or ratio.

Parameters:
identifierstr

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 identifier tags.

ratio(identifier, **kwargs)[source]#

Plot a model ratio.

Parameters:
identifierstr

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 identifier tags.