Plotting#
We have implemented a number of plotting functions in lightning to make visualizing results easy. These are typically
implemented such that they take a Lightning object as their first argument, followed by an MCMC chain (and the chain
of log-probability values, where necessary). Most plotting functions can accept dictionaries of keyword arguments
describing the colors and styles of lines, markers, etc. These are passed through to the relevant matplotlib functions.
All the plotting functions can also plot into existing axes by supplying the ax keyword (for corner_plot, set the
fig keyword instead to a figure containing the appropriate number of axes).
Two convenience items are also implemented in this module: the ModelBand class adapted from Ultranest, and the
step_curve function designed to make plotting step functions with shaded uncertainties easier. Both are mostly meant
for internal use, but are documented below for completeness.
We also provide three matplotlib style sheets (mainly for consistency across the examples) which can be loaded
using matplotlib.pyplot.style.use(name) where name is one of
[lightning-serif, lightning-sans, lightning-dark].
- class lightning.plots.ModelBand#
Bases:
objectA class interface for storing a bunch of model realizations and plotting them, as shaded bands, quantiles, or individual realizations.
This is very much taken from UltraNest’s
PredictionBandclass with some tweaks. Ultranest is (c) 2019 by Johannes Buchner, and is available under GPL v3. Find it here: https://johannesbuchner.github.io/UltraNest/All plotting functions (
shade,line,realizations) draw into the current axes unless theaxkeyword is set. The plotting functions also all pass through keyword arguments, allowing you to modify color, alpha, etc.Methods
add(y)Add a realization to the band.
line([q, ax])Draw a line at the specified quantile
q.realizations([num, replace, ax])Plot
numrandomly chosen model realizations.shade([q, ax])Draw a shaded region between the quantiles specified by
q.- __init__(x, seed=None)#
- add(y)#
Add a realization to the band. Currently limited to one at a time.
- line(q=0.5, ax=None, **kwargs)#
Draw a line at the specified quantile
q. Defaults to the median.
- realizations(num=1, replace=False, ax=None, **kwargs)#
Plot
numrandomly chosen model realizations. Ifreplaceis set, the same realization can be chosen multiple times.
- shade(q=(0.16, 0.84), ax=None, **kwargs)#
Draw a shaded region between the quantiles specified by
q. Defaults to the 68% interval.
- lightning.plots.chain_plot(lgh, samples, plot_median=True, median_color='darkorange', **kwargs)#
Produce a chain plot of samples from an SED fit.
The chain plots are placed in a single matplotlib figure, all in a single column. Not that this may (will) be unwieldy in cases with many free parameters.
- Parameters:
- lghlightning.Lightning object
Used to assign names (and maybe units) to the sample dimensions.
- samplesnp.ndarray, (Nsamples, Nparam), float
The sampled parameters. Note that this should also include any constant parameters.
- plot_medianbool
If true, draw a horizontal line at the median of the chain.
- median_colorstring
The color to plot the median line with.
- **kwargsdict
Keyword arguments are passed on to plt.plot for the chain plot.
- Returns:
- figMatplotlib figure containing the plot
- axsList of axes in the plot
- lightning.plots.corner_plot(lgh, samples, **kwargs)#
Produce a corner plot of samples from an SED fit.
This is just a thin wrapper around corner that just figures out which dimensions are constant and assigns parameter labels to the chains. See the link below for a complete listing of keywords understood by corner.
- Parameters:
- lghlightning.Lightning object
Used to assign names (and maybe units) to the sample dimensions.
- samplesnp.ndarray, (Nsamples, Nparam), float
The sampled parameters. Note that this should also include any constant parameters.
- **kwargsdict
Keyword arguments are passed on to corner.corner.
- Returns:
- figMatplotlib figure containing the plot
References
- lightning.plots.sed_plot_bestfit(lgh, samples, logprob_samples, plot_components=False, plot_unatt=False, ax=None, xlim=(0.1, 1200), ylim=(9000000.0, None), xlabel='Observed-Frame Wavelength $[\\rm \\mu m]$', ylabel='$\\nu L_{\\nu}\\ [\\rm L_\\odot]$', stellar_unatt_kwargs={'color': 'dodgerblue', 'label': 'Unattenuated stellar pop.'}, stellar_att_kwargs={'color': 'red', 'label': 'Attenuated stellar pop.'}, agn_kwargs={'color': 'darkorange', 'label': 'AGN'}, dust_kwargs={'color': 'green', 'label': 'Dust'}, total_kwargs={'color': 'slategray', 'label': 'Total model'}, data_kwargs={'capsize': 2, 'color': 'k', 'label': 'Data', 'linestyle': '', 'marker': 'D', 'markerfacecolor': 'k'}, show_legend=True, legend_kwargs={'frameon': False, 'loc': 'upper right'}, uplim_sigma=3, uplim_kwargs={'color': 'k', 'marker': '$\\downarrow$'})#
Best-fit SED plot.
Selects the highest log-probability model from the chain. Individual components may be plotted.
- Parameters:
- lghlightning.Lightning object
Used to assign names (and maybe units) to the sample dimensions.
- samplesnp.ndarray, (Nsamples, Nparam), float
The sampled parameters. Note that this should also include any constant parameters.
- logprob_samplesnp.ndarray, (Nsamples,), float
Log-probability chain.
- plot_componentsbool
If
True, plot the components of the SED.- plot_unattbool
If
True, also plot the unattenuated stellar SED.- axmatplotlib.axes.Axes
Axes to draw the plot in. (Default: None)
- xlimtuple
- ylimtuple
- xlabelstr
- ylabelstr
- stellar_unatt_kwargsdict
- stellar_att_kwargsdict
- agn_kwargsdict
- dust_kwargsdict
- total_kwargsdict
- data_kwargsdict
- show_legendbool
- legend_kwargsdict
- uplim_sigmaint
How many sigma should upper limits be drawn at? (Default: 3)
- uplim_kwargsdict
Each of the above
*_kwargsparameters is a dict containing keyword arguments describing the color, style, label, etc. of the corresponding plot element, passed through to the appropriatematplotlibfunction.
- Returns:
- figMatplotlib figure containing the plot
- axAxes containing the plot
- lightning.plots.sed_plot_delchi(lgh, samples, logprob_samples, ax=None, xlim=(0.1, 1200), ylim=(-5.1, 5.1), lines=[0, -1, 1], linecolors=['slategray'], linestyles=['-', '--', '--'], xlabel='Observed-Frame Wavelength $[\\rm \\mu m]$', ylabel='Residual $[\\sigma]$', data_kwargs={'capsize': 2, 'color': 'k', 'label': 'Data', 'linestyle': '', 'marker': 'D', 'markerfacecolor': 'k'}, uplim_sigma=3, uplim_kwargs={'color': 'k', 'marker': '$\\downarrow$'})#
Delta-chi residuals for the best-fit SED.
\[\delta \chi = (L^{\rm obs}_\nu - L^{\rm mod}_\nu) / \sigma\]Selects the highest log-probability model from the chain.
- Parameters:
- lghlightning.Lightning object
Used to assign names (and maybe units) to the sample dimensions.
- samplesnp.ndarray, (Nsamples, Nparam), float
The sampled parameters. Note that this should also include any constant parameters.
- logprob_samplesnp.ndarray, (Nsamples,), float
Log-probability chain.
- xlimtuple
- ylimtuple
- lineslist or tuple
Values to draw horizontal guide lines at (in sigma). (Default: [-1,0,1])
- linecolorslist or str
Corresponding colors for the guide lines. (Default: ‘slategray’)
- linestyleslist or str
Corresponding styles for the guide lines. (Default: [‘-’, ‘–’, ‘–‘])
- xlabelstr
- ylabelstr
- data_kwargsdict
- uplim_sigmaint
How many sigma should upper limits be drawn at? (Default: 3)
- uplim_kwargsdict
Each of the above
*_kwargsparameters is a dict containing keyword arguments describing the color, style, label, etc. of the corresponding plot element, passed through to the appropriatematplotlibfunction.
- Returns:
- figMatplotlib figure containing the plot
- axAxes containing the plot
- lightning.plots.sed_plot_morebayesian(lgh, samples, logprob_samples, plot_components=False, plot_unatt=False, ax=None, xlim=(0.1, 1200), ylim=(9000000.0, None), xlabel='Observed-Frame Wavelength $[\\rm \\mu m]$', ylabel='$\\nu L_{\\nu}\\ [\\rm L_\\odot]$', stellar_unatt_kwargs={'alpha': 0.5, 'color': 'dodgerblue', 'label': 'Unattenuated stellar pop.'}, stellar_att_kwargs={'alpha': 0.5, 'color': 'red', 'label': 'Attenuated stellar pop.'}, agn_kwargs={'alpha': 0.5, 'color': 'darkorange', 'label': 'AGN'}, dust_kwargs={'alpha': 0.5, 'color': 'green', 'label': 'Dust'}, total_kwargs={'alpha': 0.5, 'color': 'slategray', 'label': 'Total model'}, data_kwargs={'capsize': 2, 'color': 'k', 'label': 'Data', 'linestyle': '', 'marker': 'D', 'markerfacecolor': 'k'}, show_legend=True, legend_kwargs={'frameon': False, 'loc': 'upper right'}, uplim_sigma=3, uplim_kwargs={'color': 'k', 'marker': '$\\downarrow$'})#
More bayesian visualization of the fit, agnostic of the best fit. Better name TBD
Shows the 16th-84th percentile range of the model Lnu. Currently this doesn’t show the median or best-fit, just shaded polygons indicating the range.
- Parameters:
- lghlightning.Lightning object
Used to assign names (and maybe units) to the sample dimensions.
- samplesnp.ndarray, (Nsamples, Nparam), float
The sampled parameters. Note that this should also include any constant parameters.
- logprob_samplesnp.ndarray, (Nsamples,), float
Log-probability chain.
- plot_componentsbool
If
True, plot the components of the SED.- plot_unattbool
If
True, also plot the unattenuated stellar SED.- axmatplotlib.axes.Axes
Axes to draw the plot in. (Default: None)
- xlimtuple
- ylimtuple
- xlabelstr
- ylabelstr
- stellar_unatt_kwargsdict
- stellar_att_kwargsdict
- agn_kwargsdict
- dust_kwargsdict
- total_kwargsdict
- data_kwargsdict
- show_legendbool
- legend_kwargsdict
- uplim_sigmaint
How many sigma should upper limits be drawn at? (Default: 3)
- uplim_kwargsdict
Each of the above
*_kwargsparameters is a dict containing keyword arguments describing the color, style, label, etc. of the corresponding plot element, passed through to the appropriatematplotlibfunction.
- Returns:
- figMatplotlib figure containing the plot
- axAxes containing the plot
- lightning.plots.sfh_plot(lgh, samples, xlabel='Lookback Time $t$ [yr]', ylabel='SFR$(t)$ $[\\rm M_{\\odot}\\ yr^{-1}]$', ax=None, shade_band=True, shade_q=(0.16, 0.84), shade_kwargs={'alpha': 0.3, 'color': 'k', 'zorder': 0}, plot_line=True, line_q=0.5, line_kwargs={'color': 'k', 'zorder': 1}, ylim=None)#
A plot of the posterior SFR as a function of time.
The default behavior is to plot the median of the posterior along with the shaded 16th to 84th percentiles.
- Parameters:
- lghlightning.Lightning object
Used to assign names (and maybe units) to the sample dimensions.
- samplesnp.ndarray, (Nsamples, Nparam), float
The sampled parameters. Note that this should also include any constant parameters.
- xlabelstr
- ylabelstr
- axmatplotlib.axes.Axes
Axes to draw the plot in. (Default: None)
- shade_bandbool
Should the uncertainty band be shaded?
- shade_qtuple
Quantiles to shade between. (Default: (0.16, 0.84))
- shade_kwargsdict
- plot_linebool
Should a line be plotted?
- line_q
Quantile to plot the line at (Default: 0.5)
- line_kwargsdict
Each of the above
*_kwargsparameters is a dict containing keyword arguments describing the color, style, label, etc. of the corresponding plot element, passed through to the appropriatematplotlibfunction.- ylimtuple
- Returns:
- figMatplotlib figure containing the plot
- axAxes containing the plot
- lightning.plots.step_curve(bin_edges, y_values, anchor=False)#
From a histogram (bin edges and count values) generate a step curve for use with matplotlib’s
plotfunction.This function takes an array of N + 1 bin edges and an array of N values and turns them into a list of 2N vertices so that you can make a step plot with the
plotcommand rather thanstep,hlinesandvlines, etc.- Parameters:
- bin_edgesnumpy array, (N+1), float
Array defining the edges of the histogram bins (i.e., the locations of the steps). Assumed to be a monotonically increasing sequence.
- y_valuesnumpy array, (…, N), float
Array containing the y values corresponding to bin_edges: the value of the function on (bin_edges[i], bin_edges[i+1]) is y_values[…,i]. Note that this can be a 2D array, where the first axis cycles among different curves.
- anchorbool (default False)
If True, the returned curve will be anchored to 0 on both sides.
- Returns:
- xnp.ndarray
- ynp.ndarray
Two numpy arrays containing the x- and y-values of the step curve, respectively. See note on size below.
Notes
If anchor is False, each curve has 2N points, where N is the number of y-values.
If anchor is True, each curve has 2N + 2 points.
This function actually doesn’t do any plotting, it just makes arrays to feed into
plot.