Plotting spectra¶
General plotting¶
- penguins.subplots(*args, **kwargs)¶
Direct wrapper around
plt.subplots()
.
- penguins.subplots2d(nrows=1, ncols=1, height_ratios=None, width_ratios=None, **kwargs)¶
Wrapper around matplotlib’s
plt.subplots()
function, which (in addition to performing everythingplt.subplots()
does) also sets the figure size to(4 * ncols)
by(4 * nrows)
by default. This means that every subplot will have an area of 4 inches by 4 inches, which is a good size for 2D spectra.Also accepts the gridspec keyword arguments
height_ratios
andwidth_ratios
. The effect of this is that each subplot will have a height equal to the height_ratio times 4, i.e. if one specifiesheight_ratios = [0.5, 1]
then the top row will be 2 inches tall and the bottom row 4 inches tall.- Parameters:
- nrowsint, optional
Number of rows.
- ncolsint, optional
Number of columns.
- height_ratioslist of float, optional
Ratios of Axes heights.
- width_ratioslist of float, optional
Ratios of Axes widths.
- kwargsdict, optional
Other keyword arguments passed to
plt.subplots()
. Note that if either height_ratios or width_ratios are passed, they will override both the figsize as well as gridspec_kw keyword arguments.
- Returns:
- figFigure
Figure
instance corresponding to the current plot.- axsAxes, or ndarray of Axes
If only one subplot was requested, this is the
Axes
instance. Otherwise this is anndarray
ofAxes
, one for each subplot. See the documentation ofplt.subplots()
for further explanation.
- penguins.mkplot(ax=None, empty_pha=True, **kwargs)¶
Construct a plot from one or more staged spectra.
- Parameters:
- axAxes, optional
Axes
instance to plot the spectra on. If not provided, creates newFigure
andAxes
instances.- kwargsdict, optional
Keyword arguments that are passed on to
_mkplot1d()
or_mkplot2d()
respectively, depending on the dimensionality of the spectrum being plotted. In turn, these are passed on toAxes.plot
orAxes.contour
.
- Returns:
- Other Parameters:
- empty_phabool, optional
Whether to empty the
PlotHoldingArea
of theAxes
after constructing the plots. The average user should have no use for this; it only exists to makefind_baselev()
work.
See also
penguins.pgplot._mkplot1d
Keyword arguments for 1D plots are described here.
penguins.pgplot._mkplot2d
Keyword arguments for 2D plots are described here.
Notes
This function itself does not do very much. It mainly performs setup and teardown actions, whereas the actual plotting itself is delegated to
_mkplot1d()
and_mkplot2d()
. (Those functions should not be used directly.)
- penguins.mkplots(axs=None, titles=None, **kwargs)¶
Convenience function which essentially calls mkplot(ax, title=title) for ax, title in zip(axs.flat, titles).
- Parameters:
- axslist, tuple, or ndarray of Axes (optional)
If not passed, will iterate over all Axes in the currently active figure. >1D arrays (e.g. those returned by
subplots()
) are allowed.- titleslist or tuple of str (optional)
A series of subplot titles. Use None or an empty string to not have a a title.
- **kwargsdict
Other keyword arguments which are passed on to
mkplot()
(and consequently the other functions that it calls).
- Returns:
- figFigure
Figure
instance for the active plot.- axsndarray of Axes
The same ndarray that was provided.
- penguins.mkinset(ax, pos, size, transform=None, show_zoom=True, parent_corners=('sw', 'se'), inset_corners=('sw', 'se'), inset_options=None)¶
Creates an inset Axes on a given Axes instance. Spectra can be staged on this Axes, and
mkplot
can be called, just as usual.- Parameters:
- axAxes
Axes
instance to construct the inset inside.- pos(float, float)
Position of lower-left corner of inset axes given as (x, y).
- size(float, float)
Size of inset axes, given as (width, height).
- transformTransform
Transform
to use for specifying the coordinates of pos and size. By default, axes coordinates are used for both.- show_zoombool, optional
Whether to draw lines between the parent and inset axes (to indicate the section of the spectrum zoomed into).
- parent_corners(str, str), optional
Corners of the parent axes to draw the zoom lines from. Each element of the tuple can be chosen from {“southwest”, “southeast”, “northeast”, “northwest”, “sw”, “se”, “ne”, “nw”}.
- inset_corners(str, str), optional
Corners of the inset axes to draw the zoom lines to.
- inset_optionsdict, optional
Dictionary of options passed to
mark_inset()
.
- Returns:
- inset_axAxes
The
Axes
instance corresponding to the inset.
- penguins.tight_layout(*args, **kwargs)¶
Direct wrapper around
plt.tight_layout()
.
- penguins.show(*args, **kwargs)¶
Direct wrapper around
plt.show()
.
- penguins.savefig(*args, **kwargs)¶
Direct wrapper around
plt.savefig()
.
- penguins.pause(*args, **kwargs)¶
Direct wrapper around
plt.pause()
.
1D plotting interfaces¶
- penguins.pgplot._stage1d(dataset, ax=None, scale=1, bounds='', dfilter=None, label=None, color=None, **kwargs)¶
Stages a 1D spectrum.
This constructs a
PlotObject1D
object from the dataset as well as any options passed via the keyword arguments, and adds it to the plot queue of theAxes
.Note that the preferred way of staging spectra is to call the
stage()
method on the dataset object.- Parameters:
- datasetDataset1D, Dataset1DProj, or Dataset1DProjVirtual
Dataset to be staged.
- axAxes, optional
Axes
instance to tie the plot to. Defaults to the currently active Axes.- scalefloat, optional
Value to scale the spectrum intensity by.
- boundsstr or (float, float), optional
Region of the spectrum to plot. If given as a string, should be in the form
lower..upper
, wherelower
andupper
are both chemical shifts. If given as a tuple, should be in the form(lower, upper)
. Eitherlower
orupper
can be omitted (in the string) or passed asNone
(in the tuple) to avoid giving a lower or upper bound. If not given, the entire spectrum is plotted.- dfilterfunction :: float -> bool, optional
Function which takes the intensity at each point as its only parameter and returns a boolean. If it returns True, the point is plotted, and if it returns False, the point is not plotted.
- labelstr, optional
Label to be used in the plot legend.
- colorstr, optional
Color to use for plotting.
- **kwargs
Any other keyword arguments are passed as-is to
Axes.plot
.
- Returns:
- None
See also
penguins.dataset._1D_PlotMixin.stage
Equivalent method on
Dataset1D
,Dataset1DProj
, andDataset1DProjVirtual
objects, and the preferred way to stage spectra.
- penguins.pgplot._mkplot1d(ax=None, style='1d', tight_layout=None, stacked=False, voffset=0, hoffset=0, title=None, autolabel='nucl', xlabel=None, ylabel=None, legend_loc='best', units='ppm')¶
Calls
Axes.plot
on all the spectra in the plot queue. All hoffset and voffset calculations are performed here.Note that this function should never be called directly.
- Parameters:
- axAxes, optional
Axes
instance to plot the spectra on. If not provided, creates a newFigure
andAxes
.- stylestr, optional
Plot style to use. By default this is
1d
. For the list of plot styles, seestyle_axes()
.- tight_layoutbool, optional
Whether to call plt.tight_layout() after constructing the plot. By default this is set to True unless the Figure has been set up with
constrained_layout
(see matplotlib’s tutorials/intermediate/constrainedlayout_guide).- stackedbool, optional
True to make spectra tightly stacked vertically (i.e. not superimposed). If True, overrides any value passed in voffset.
- voffsetfloat or list of float, optional
If given as a float, indicates the amount of vertical offset between spectra, in units of the maximum height. The height of a spectrum refers to the total width it spans in the y-axis, and the maximum height refers to the largest such height of all spectra in the plot queue. Using a float for
voffset
is useful for offsetting spectra by a constant amount. Note that stacked spectra will have a variable vertical offset between each spectrum, because each spectrum will have a different height. If given as a list, each staged spectrum is offset by the corresponding amount (again, this is given in units of maximum height).- hoffsetfloat or list of float, optional
If given as a float, indicates the horizontal offset between adjacent spectra. If this is positive, then successive spectra are shifted towards the right (the first spectrum is not shifted). If given as a list, each staged spectrum is offset by the corresponding amount (in ppm).
- titlestr, optional
Plot title.
- autolabelstr, optional (default: “nucl”)
Automatic label to use for the x-axis (the y-axis is always set to empty). The only option available now is
nucl
(the default), which generates a LaTeX representation of the nucleus of the first staged spectrum (e.g. for a proton spectrum, using this would automatically generate the x-axis labelr"$\rm ^{1}H$ (ppm)"
).- xlabelstr, optional
x-Axis label. Overrides the autolabel parameter if given.
- ylabelstr, optional
y-Axis label. Overrides the autolabel parameter if given.
- legend_locstr or (float, float), optional
Location to place the legend. This is passed as the loc parameter to
Axes.legend
; see the documentation there for the available options.- unitsstr from {“ppm”, “Hz”}, default “ppm”
Units to use for plotting. This also determines the units for the hoffset parameter: if units is
ppm
then hoffset is interpreted as a chemical shift offset, and vice versa.
- Returns:
See also
penguins.mkplot
You should call
pg.mkplot(ax)
instead of using this_mkplot1d
function directly.
2D plotting interfaces¶
- penguins.pgplot._stage2d(dataset, ax=None, f1_bounds='', f2_bounds='', levels=(None, None, None), colors=(None, None), dfilter=None, label=None, **kwargs)¶
Stages a 2D spectrum.
This constructs a
PlotObject2D
object from the dataset as well as any options passed via the keyword arguments, and adds it to the plot queue of theAxes
.Note that the preferred way of staging spectra is to call the
stage()
method on the dataset object.- Parameters:
- datasetDataset1D, Dataset1DProj, or Dataset1DProjVirtual
Dataset to be staged.
- axAxes, optional
Axes
instance to tie the plot to. Defaults to the currently active Axes.- scalefloat, optional
Value to scale the spectrum intensity by.
- f1_boundsstr or (float, float), optional
Region of the indirect chemical shifts to plot. If given as a string, should be in the form
lower..upper
, wherelower
andupper
are both chemical shifts. If given as a tuple, should be in the form(lower, upper)
. Eitherlower
orupper
can be omitted (in the string) or passed asNone
(in the tuple) to avoid giving a lower or upper bound. If not given, the entire range of indirect chemical shifts is plotted.- f2_boundsstr or (float, float), optional
Same as f1_bounds, but for the direct dimension.
- levelsfloat or (float, float, float), optional
A tuple (baselev, increment, nlev) specifying the levels at which to draw contours. These represent, respectively, the lowest contour level, the multiplicative increment between adjacent contours, and the number of contour levels to draw. Contours are always drawn for both positive and negative levels.
If any of these are None, then the default values are used: for baselev this is TopSpin’s default contour level, for increment this is 1.5, and for nlev this is 10. Alternatively, can be provided as a single float baselev as shorthand for (baselev, None, None).
- dfilterfunction :: float -> bool, optional
Function which takes the intensity at each point as its only parameter and returns a boolean. If it returns True, the point is plotted, and if it returns False, the point is not plotted.
- labelstr, optional
Label to be used in the plot legend.
- color(str, str), optional
Colors to use for positive and negative contours respectively.
- **kwargs
Any other keyword arguments are passed as-is to
Axes.contour
. Note that these will be overridden by other keyword arguments passed to stage().
- Returns:
- None
See also
_2D_PlotMixin.stage
Equivalent method on Dataset2D objects, and the preferred way of staging spectra.
- penguins.pgplot._mkplot2d(ax=None, style='2d', tight_layout=None, offset=(0, 0), title=None, autolabel='nucl', xlabel=None, ylabel=None, legend_loc='best', f1_units='ppm', f2_units='ppm')¶
Calls
Axes.contour
on all the spectra in the plot queue. All offset calculations are performed here.Note that this function should never be called directly.
- Parameters:
- axAxes, optional
Axes
instance to plot the spectra on. If not provided, creates a newFigure
andAxes
.- stylestr, optional
Plot style to use. By default this is
2d
. For the list of plot styles, seestyle_axes()
.- tight_layoutbool, optional
Whether to call plt.tight_layout() after constructing the plot. By default this is set to True unless the Figure has been set up with
constrained_layout
(see matplotlib’s tutorials/intermediate/constrainedlayout_guide).- offset(float, float), optional
Amount to offset successive spectra by in units of ppm, provided as (f1_offset, f2_offset).
- titlestr, optional
Plot title.
- autolabelstr, optional (default: “nucl”)
Automatic label to use for the x-axis. The
nucl
option generates a LaTeX representation of the nuclei of the first spectrum (e.g. for a C–H HSQC, using this would automatically generate the x- and y-axis labelsr"$\rm ^{1}H$ (ppm)"
andr"$\rm ^{13}C$ (ppm)"
respectively). Thef1f2
option generates genericf1 (ppm)
andf2 (ppm)
strings. There are no other options for now.- xlabelstr, optional
x-Axis label. If either xlabel or ylabel are set, they will override the autolabel parameter (if only one is set then the other axis label will be empty!).
- ylabelstr, optional
y-Axis label.
- legend_locstr or (float, float), optional
Location to place the legend. This is passed as the loc parameter to
Axes.legend
; see the documentation there for the available options.- f1_unitsstr from {“ppm”, “Hz”}, default “ppm”
Units to use for the f1 dimension. This also determines the units for the first value of the offset parameter: if units is
ppm
then offset[0] is interpreted as a chemical shift offset, and vice versa.- f2_unitsstr from {“ppm”, “Hz”}, default “ppm”
Units to use for the f2 dimension. Likewise, this determines the units for the second value of the offset parameter.
- Returns:
See also
penguins.mkplot
You should call
pg.mkplot(ax)
instead of using this_mkplot1d
function directly.
- penguins.pgplot._find_baselev(dataset, increment=None, nlev=4)¶
Create an interactive slider window to see the effect of changing baselev on the displayed spectrum.
Note that this should not be called directly; use the
find_baselev()
method onDataset2D
objects instead.- Parameters:
- datasetDataset2D
Dataset to stage.
- incrementfloat, optional
Multiplicative increment between adjacent contour levels. This is typically not worth changing.
- nlevint, optional
Number of contour levels to use. This is not typically worth changing. If you really want to, don’t go too high, as this causes the plot to be very laggy. (It has to call
Axes.contour
every time the slider is moved.)
- Returns:
- chosen_baselevfloat
Final value of the baselev before the ‘OK’ button was pressed.
See also
penguins.dataset._2D_PlotMixin.find_baselev
Equivalent method on
Dataset2D
objects. Usage of this is preferred.
Auxiliary plotting utilities¶
- penguins.label_axes(axs, pos='upper left', offset=(0.02, 0.02), form='a', start=1, fstr='{}', **kwargs)¶
Adds consecutive labels to the corners of a series of
Axes
. Useful for creating numbered plots.- Parameters:
- axssequence of
Axes
- posstr, default {“upper left”}
The location to place the text at. Right now the only option is the upper left corner.
- offset(float, float), default (0.02, 0.02)
The horizontal and vertical offsets from the edges of the Axes, in Axes coordinates. In other words, the default offset places 2% of space between the edge of the Axes and the text.
- formstr from {“a”, “A”, “i”, “I”, “1”}, default “a”
The numbers, or characters, to use for numbering. The alphabet work up to 26 times (i.e. ‘z’). Roman numerals work up to 26 (i.e. ‘xxvi’). If you need more than that, you’re probably doing your plots wrongly.
- startint, default 1
The number to start from. Values below 1 are ignored.
- fstrstr, default “{}”
A format string with a single field. The actual string placed on the axes will be
fstr.format(ctr)
, where ctr is the actual counter (i.e. 123… or abc…) which is internally generated based on the form argument. Thus, if you want your graphs to be labelled(a)
,(b)
, … set fstr to be"({})"
, for example.- **kwargsdict
Optional parameters which are passed to ax.text(). If there is a clash, the parameters passed here will override choices made using the other keyword arguments. For example, if you want your text in the middle of the spectrum, you can call
label_axes(..., x=0.5, y=0.5)
.
- axssequence of
- penguins.style_axes(ax, style, tight_layout=None)¶
Styles the given
Axes
instance according to the requested style.This is useful for making sure that all subplots in a series have a uniform appearance.
- Parameters:
- axAxes
Axes
instance to style.- stylestr
Style to be applied. The available options are
1d
,1d_box
,2d
,plot
, andnatural
.- tight_layoutbool, optional
Whether to call plt.tight_layout() after constructing the plot. By default this is set to True unless the Figure has been set up with
constrained_layout
(see matplotlib’s tutorials/intermediate/constrainedlayout_guide).
- Returns:
- None
- penguins.xmove(ax=None, pos='right', remove_ticks=0, tight_layout=None, dx=0, dy=0)¶
Utility function which moves the Axes x-label and x-axis ticks to one of several preset configurations.
- Parameters:
- ax
Axes
or iterable thereof, default currently active Axes The Axes instance to apply the changes to. If an iterable is provided, applies changes to all Axes in it.
- posstr, default “right”
The position of the x-axis label. The only option currently supported is “right”, which places the x-axis label at the bottom-right of the x-axis.
- tight_layoutbool, optional
Whether to call plt.tight_layout() after constructing the plot. By default this is set to True unless the Figure has been set up with
constrained_layout
(see matplotlib’s tutorials/intermediate/constrainedlayout_guide).- dxfloat, default 0
Amount to horizontally shift the resulting x-axis label by, expressed in terms of Axes coordinates (i.e. 0 is left-most part of Axes and 1 is right-most). Positive numbers shift the label to the right and vice versa. This should generally not be needed but can be useful for tweaking the layout if the result is not satisfactory.
- dyfloat, default 0
Amount to vertically shift the resulting x-axis label by, expressed in terms of Axes coordinates. Positive numbers shift the label up.
- ax
- penguins.ymove(ax=None, pos='topright', tight_layout=None, dx=0, dy=0)¶
Utility function which moves the Axes y-label and y-axis ticks to one of several preset configurations.
- Parameters:
- ax
Axes
or iterable thereof, default currently active Axes The Axes instance to apply the changes to. If an iterable is provided, applies changes to all Axes in it.
- posstr from {“topright”, “midright”, “topspin”}, default “topright”
The configuration of the y-axis. This is better explained through a picture than in words.
- tight_layoutbool, optional
Whether to call plt.tight_layout() after constructing the plot. By default this is set to True unless the Figure has been set up with
constrained_layout
(see matplotlib’s tutorials/intermediate/constrainedlayout_guide).- dxfloat, default 0
Amount to horizontally shift the resulting y-axis label by, expressed in terms of Axes coordinates (i.e. 0 is left-most part of Axes and 1 is right-most). Positive numbers shift the label to the right and vice versa. This should generally not be needed but can be useful for tweaking the layout if the result is not satisfactory.
- dyfloat, default 0
Amount to vertically shift the resulting y-axis label by, expressed in terms of Axes coordinates. Positive numbers shift the label up.
- ax
- penguins.cleanup_axes()¶
Hides any axis tick labels which collide with axis labels.
- penguins.cleanup_figure(padding=0.02)¶
- penguins.set_palette(palette)¶
Sets the currently active color palette. The default palette is seaborn’s
deep
.The palette is used both for staging successive 1D spectra, as well as for any plots done with seaborn. For 2D spectra, colors from seaborn’s
bright
palette have been manually chosen. If you want to override these, you should directly pass the colors parameter to the stage() method.- Parameters:
- palettestr or list of str
Color palette to use. See tutorial/color_palettes for a full description of the possible options.
- Returns:
- None
- penguins.color_palette(palette=None)¶
Returns a list of colors corresponding to a color palette. If palette is not provided, returns the colors in the current color palette.
This is essentially a wrapper around
sns.color_palette
, but it only offers one argument, and it can’t be used as a context manager. Useset_palette
if you want to change the active palette.- Parameters:
- palettestr or list of str, optional
The palette to look up. Defaults to the currently active color palette.
- Returns:
- colorslist of str
The colors in the current color palette.
- class penguins.pgplot.PlotHoldingArea¶
Plot holding area which holds staged spectra (as
PlotObject1D
orPlotObject2D
objects) before the plot is constructed usingmkplot()
.Each
Axes
has its own PlotHoldingArea instance, which can be accessed withax.pha
.- Attributes:
- plot_objslist
List of
PlotObject1D
orPlotObject2D
items which have been staged.- colors_1dgenerator object
Yields colors one at a time from the currently active palette.
- colors_2dgenerator object
Yields selected tuples (positive, negative) of colors, taken from the “bright” palette.
- class penguins.pgplot.PlotProperties¶
Stores properties of 1D spectra that have already been plotted using
mkplot()
. Only artists are stored for 2D spectra.Each
Axes
has its own PlotProperties instance, which can be accessed withax.prop
(but only aftermkplot()
has been called on that particular Axes).- Attributes:
- hoffsetslist of float
Horizontal offset of each plotted spectrum in ppm.
- voffsetslist of float
Vertical offset of each plotted spectrum in data coordinates (because the y-axis of a 1D spectrum is the intensity, this is typically on the order of 1e5).
- colorslist of str
List of colors used for each spectrum.
- optionslist of dict
List of options passed to
Axes.plot
for each individual spectrum.- artistslist of Artists
List of
Artist
objects that have been plotted on the currentAxes
. For 1D spectra, these are Line2D objects; for 2D spectra, they are QuadContourSet objects.
- class penguins.pgplot.PlotObject1D(dataset, ax, scale=1, bounds='', dfilter=None, label=None, color=None, plot_options=None)¶
Object that includes a 1D dataset as well as other keyword arguments passed to
_stage1d()
.Any processing done on the spectrum, e.g. scaling, bounds selection, or dfilter, is done when this class is initialised.
- class penguins.pgplot.PlotObject2D(dataset, ax, f1_bounds='', f2_bounds='', levels=(None, None, None), colors=(None, None), dfilter=None, label=None, plot_options=None)¶
Object that includes a 2D dataset as well as other keyword arguments passed to
_stage2d()
.Any processing done on the spectrum, e.g. bounds selection, or dfilter, is done when this class is initialised. The contour levels and colors are also generated by this class.