mzapy.view

This module defines functions for interactive viewing and/or generating plots of extracted data. Plotting functions are implemented to maintain a consistent look and feel, with a flexible interface that allows for customization or generating more complex plots when needed.

Flexible Plotting System

The plotting functions in this module all implement an interface that allows for flexibility in how plots are generated. Each plotting function takes as input some data to plot with some customization/configuration parameters (things like line color, etc.), in addition to the ax and figname kwargs which control how the plot is constructed and what is done with the plot. figname, when provided, can be set to "show" or an image file name which prompts the plotting function to display the plot interactively or save it to file, respectively. If no figname is provided, however, instead of viewing or saving the plot the plotting function will return a matplotlib.pyplot.Axes instance so that further customization can be performed or more data can be plotted in the same panel. The ax kwarg, when provided, tells the plotting function to skip setup/customization, and instead just plot the data into the provided matplotlib.pyplot.Axes instance. Custom plotting functions can be implemented with this same interface by using the mzapy.view._setup_and_save_or_show_plot() decorator (see documentation for template plotting function).

Below is a script with several examples demonstrating how to construct different plots using the same function but with different parameters using this flexible plotting system

Example of flexible plotting system (using plot_spectrum function)
import numpy as np
from matplotlib import pyplot as plt

from mzapy.view import plot_spectrum

def make_some_fake_data():
    mz = np.linspace(100, 500, 1001)
    i1 = np.abs(np.random.normal(size=mz.shape)) * 10000
    i2 = np.abs(np.random.normal(size=mz.shape)) * 10000
    return mz, i1, i2

def main():
    # arbitrary arrays meant to mimic mass spectrum data
    # one array of m/z and two arrays of intensities
    mz, i1, i2 = make_some_fake_data()

    # do a single plot, no label, default figsize, show it
    plot_spectrum(mz, i1, [380, 400], figname='show')

    # do a single plot, no label, different figsize, show it
    plot_spectrum(mz, i1, [380, 390], figname='show', figsize=[2.22, 2.22])

    # do a single plot, label it, different figsize, show it
    plot_spectrum(mz, i1, [380, 390], label='foo', figname='show', figsize=[2.22, 2.22])

    # do a single plot, label it, different figsize, save it
    plot_spectrum(mz, i1, [380, 390], label='foo', figname='figures/test01.png', figsize=[2.22, 2.22])

    # do a combined plot, with labels, different figsize, show it
    ax = plot_spectrum(mz, i1, [380, 400], label='foo', figsize=[4, 2])
    plot_spectrum(mz, i2, c='r', label='bar', ax=ax, figname='show')

    # do a combined plot, with labels, different figsize, save it
    ax = plot_spectrum(mz, i1, [380, 400], label='foo', figsize=[4, 2])
    plot_spectrum(mz, i2, c='r', label='bar', ax=ax, figname='figures/test02.png')

    # do a combined plot, with labels, different figsize, add some bars to it, save it
    ax = plot_spectrum(mz, i1, [380, 400], label='foo', figsize=[4, 2])
    ax = plot_spectrum(mz, i2, c='r', label='bar', ax=ax)
    ax.bar([384, 386, 388, 390, 392, 394],
        [20000, 16000, 12800, 10240, 8192, 6554],
        width=0.2, color='g', label='baz')
    ax.legend(frameon=False)  # need to add in the legend since that is only added when showing/saving
    plt.tight_layout()
    plt.savefig('figures/test03.png', dpi=350, bbox_inches='tight')
    plt.close()

    # plot each trace in separate panels, with labels, add bars to both, save it
    fig, axs = plt.subplots(nrows=2, figsize=(3.33, 3.33))
    ax0 = plot_spectrum(mz, i1, [380, 400], label='foo', ax=axs[0], ign_newax=True)
    ax0.bar([384, 386, 388, 390, 392, 394],
            [20000, 16000, 12800, 10240, 8192, 6554],
            width=0.2, color='g', label='baz')
    ax0.legend(frameon=False)  # need to add in the legend since that is only added when showing/saving
    ax1 = plot_spectrum(mz, i1, [380, 400], c='r', label='bar', ax=axs[1], ign_newax=True)
    ax1.bar([384, 386, 388, 390, 392, 394],
            [20000, 16000, 12800, 10240, 8192, 6554],
            width=0.2, color='g', label='baz')
    ax1.legend(frameon=False)  # need to add in the legend since that is only added when showing/saving
    plt.tight_layout()
    plt.savefig('figures/test04.png', dpi=350, bbox_inches='tight')
    plt.close()


if __name__ == '__main__':
    main()

The images below are the last two plots from the above code example.

(single panel)

Example of mass spectrum with bars added

(two panels)

Example of mass spectrum with bars added, 2 panels

Module Reference

Viewing Data

mzapy.view.plot_spectrum(mz, i, mz_range=None, c='b', ls='-', **kwargs)

generate a plot of a mass spectrum (mz vs. i)

Parameters:
mznumpy.ndarray(float)
inumpy.ndarray(float)

m/z and intensity components of the mass spectrum

mz_rangetuple(float), optional

if provided, sets m/z bounds to display from spectrum

cstr, default=’b’

color to use for plotting spectrum, default is blue

lsstr, default=’-’

linestyle for plot, default is solid line

labelstr, optional

if provided, label for the spectrum being plotted

axmatplotlib.axes.Axes, optional

if provided, do not make new Figure and Axes instances, just plot the spectrum and format it within the provided Axes instance

fignamestr, optional

if not provided, do not save the figure or display it for interactive viewing. if figname is “show” then display the figure for interactive viewing, and if figname is a path to an image file then save the image to that path

figsizetuple(float), default=(3.33, 1.5)

figure width, height in inches. Only used when ax is not set

ign_newaxbool, default=False

when True, ignores the newax flag and performs all plot customizations regardless of whether the existing matplotlib.axes.Axes instance has already been customized

Returns:
axmatplotlib.axes.Axes or None

Axes instance for adding further customizations to the plot. Returns None if figname was provided since plt.close() gets called after interactive viewing or saving the plot so the Axes instance cannot be used after that

mzapy.view.plot_chrom(rt, i, rt_range=None, c='b', ls='-', rt_unit='min', **kwargs)

generate a plot of a chromatogram (rt vs. i)

Parameters:
rtnumpy.ndarray(float)
inumpy.ndarray(float)

retention time and intensity components of the chromatogram

rt_rangetuple(float), optional

if provided, sets retention time bounds to display from chromatogram

cstr, default=’b’

color to use for plotting chromatogram, default is blue

lsstr, default=’-’

linestyle for plot, default is solid line

rt_unitstr, default=’min’

units of retention time, default is minutes (min)

labelstr, optional

if provided, label for the chromatogram being plotted

axmatplotlib.axes.Axes, optional

if provided, do not make new Figure and Axes instances, just plot the spectrum and format it within the provided Axes instance

fignamestr, optional

if not provided, do not save the figure or display it for interactive viewing. if figname is “show” then display the figure for interactive viewing, and if figname is a path to an image file then save the image to that path

figsizetuple(float), default=(3.33, 1.5)

figure width, height in inches. Only used when ax is not set

ign_newaxbool, default=False

when True, ignores the newax flag and performs all plot customizations regardless of whether the existing matplotlib.axes.Axes instance has already been customized

Returns:
axmatplotlib.axes.Axes or None

Axes instance for adding further customizations to the plot. Returns None if figname was provided since plt.close() gets called after interactive viewing or saving the plot so the Axes instance cannot be used after that

mzapy.view.plot_atd(dt, i, dt_range=None, c='b', ls='-', dt_unit='ms', **kwargs)

generate a plot of an arrival time distribution (dt vs. i)

Parameters:
dtnumpy.ndarray(float)
inumpy.ndarray(float)

drift time and intensity components of the arrival time distribution

dt_rangetuple(float), optional

if provided, sets drift time bounds to display from arrival time distribution

cstr, default=’b’

color to use for plotting arrival time distribution, default is blue

lsstr, default=’-’

linestyle for plot, default is solid line

dt_unitstr, default=’ms’

units of drift time, default is milliseconds (ms)

labelstr, optional

if provided, label for the arrival time distribution being plotted

axmatplotlib.axes.Axes, optional

if provided, do not make new Figure and Axes instances, just plot the spectrum and format it within the provided Axes instance

fignamestr, optional

if not provided, do not save the figure or display it for interactive viewing. if figname is “show” then display the figure for interactive viewing, and if figname is a path to an image file then save the image to that path

figsizetuple(float), default=(3.33, 1.5)

figure width, height in inches. Only used when ax is not set

ign_newaxbool, default=False

when True, ignores the newax flag and performs all plot customizations regardless of whether the existing matplotlib.axes.Axes instance has already been customized

Returns:
axmatplotlib.axes.Axes or None

Axes instance for adding further customizations to the plot. Returns None if figname was provided since plt.close() gets called after interactive viewing or saving the plot so the Axes instance cannot be used after that

mzapy.view.add_peaks_to_plot(ax, peak_means, peak_heights, peak_fwhms, c='r', add_text_lbl=False, x_units='', fontsize=6)

annotate an existing plot with peaks showing their means, heights, and FWHMs as crosses, can optionally add a text label with the format {mean} +/- {FWHM / 2} {x_units} ({height})

Parameters:
axmatplotlib.axes.Axes

Axes instance containing plot to annotate with peaks

peak_meanslist(float)
peak_heightslist(float)
peak_fwhmslist(float)

peak parameters (mean, height, FWHM) as lists

cstr, default=’r’

line color for annotated peaks

add_text_lblbool, default=False

whether to annotate peaks with a text label, format: {mean} +/- {FWHM / 2} {x_units} ({height})

x_unitsstr, default=’’

when peaks are annotated with text labels, add specified units to the part of the label with the mean and FWHM

fontsizeint, default=6

when peaks are annotated with text labels, specify font size for text labels

mzapy.view._setup_and_save_or_show_plot(label, ax, figname, figsize, ign_newax)

Decorator with boilerplate for setting up then saving or showing the resulting plot. Wraps a function that plots data and applies formatting. Wrapped functions should always return the Axes instance. The parameters of the decorator set the default values for these kwargs.

template for plot_and_format function
@_setup_and_save_or_show_plot(label=None, ax=None, figname=None, figsize=(3.33, 1.5), ign_newax=False)
def plot_spectrum(mz, i, 
                  mz_range=None, c='b', 
                  **kwargs):
    # ----------
    # Parameters
    # ----------
    # xdata : ``numpy.ndarray(float)``
    # ydata : ``numpy.ndarray(float)``
    #     x and y data    
    #  ... other params ...
    # label : ``str``, optional
    #     if provided, label for the data being plotted
    # ax : ``matplotlib.axes.Axes``, optional
    #     if provided, do not make new ``Figure`` and ``Axes`` instances, just plot the spectrum and format it 
    #     within the provided ``Axes`` instance
    # figname : ``str``, optional
    #     if not provided, do not save the figure or display it for interactive viewing. if figname is "show" 
    #     then display the figure for interactive viewing, and if figname is a path to an image file then save 
    #     the image to that path
    # figsize : ``tuple(float)``, default=(3.33, 1.5)
    #     figure width, height in inches. Only used when ``ax`` is not set
    # ign_newax : ``bool``, default=False
    #     when True, ignores the newax flag and performs all plot customizations regardless of whether the existing
    #     ``matplotlib.axes.Axes`` instance has already been customized
    # -------
    # Returns
    # -------
    # ax : ``matplotlib.axes.Axes`` or ``None``
    #     ``Axes`` instance for adding further customizations to the plot. Returns None if figname was 
    #     provided since ``plt.close()`` gets called after interactive viewing or saving the plot so the 
    #     ``Axes`` instance cannot be used after that
    # -------

    # flags set by decorator
    newax = kwargs['_newax']
    ign_newax = kwargs['_ign_newax']
    ax = kwargs['ax']
    label = kwargs['label']
    ax.plot(xdata, ydata, ...)
    # apply formatting to the plot if the Axes instance is new, otherwise assume it has already been done
    # unless ign_newax is True, then ignore the newax flag
    if newax or ign_newax:
        ax.set_xlabel('X data')
        ax.set_ylabel('Y data')
        # take off the top and right borders
        for d in ['top', 'right']:
            ax.spines[d].set_visible(False)
    # always return the Axes instance, decorator will decide whether to return Axes instance or None
    return ax
Parameters:
labelstr, optional

if provided, label for the data being plotted

axmatplotlib.axes.Axes, optional

if provided, do not make new Figure and Axes instances, just plot the data and format it within the provided Axes instance

fignamestr, optional

if not provided, do not save the figure or display it for interactive viewing. if figname is “show” then display the figure for interactive viewing, and if figname is a path to an image file then save the image to that path

figsizetuple(float), default=(3.33, 2.22)

figure width, height in inches. Only used when ax is not set

ign_newaxbool, default=False

when True, ignores the newax flag and performs all plot customizations regardless of whether the existing matplotlib.axes.Axes instance has already been customized

Calibration Plots

mzapy.view.plot_mass_calibration(calibration, figname=None)

Generates a plot of a mass calibration from a fitted instance of mzapy.calibration.MassCalibration

Parameters:
calibrationmzapy.calibration.MassCalibration

fitted mass calibration instance

fignamestr, optional

if not provided, do not save the figure or display it for interactive viewing. if figname is “show” then display the figure for interactive viewing, and if figname is a path to an image file then save the image to that path

mzapy.view.plot_dtsf_ccs_calibration(calibration, figname=None)

Generates a plot of a single-filed DTIMS CCS calibration from a fitted instance of mzapy.calibration.CCSCalibrationDTsf

Parameters:
calibrationmzapy.calibration.CCSCalibrationDTsf

fitted single-field DTIMS CCS calibration instance

fignamestr, optional

if not provided, do not save the figure or display it for interactive viewing. if figname is “show” then display the figure for interactive viewing, and if figname is a path to an image file then save the image to that path

mzapy.view.plot_tw_ccs_calibration(calibration, figname=None)

Generates a plot of a TWIMS CCS calibration from a fitted instance of mzapy.calibration.CCSCalibrationTW

Parameters:
calibrationmzapy.calibration.CCSCalibrationTW

fitted TWIMS CCS calibration instance

fignamestr, optional

if not provided, do not save the figure or display it for interactive viewing. if figname is “show” then display the figure for interactive viewing, and if figname is a path to an image file then save the image to that path