Plotting and Exporting

class mrestimator.OutputHandler(data=None, ax=None)[source]

The OutputHandler can be used to export results and to create charts with timeseries, correlation-coefficients or fits.

The main concept is to have one handler per plot. It contains functions to add content into an existing matplotlib axis (subplot), or, if not provided, creates a new figure. Most importantly, it also exports plaintext of the respective source material so figures are reproducible.

Note: If you want to have a live preview of the figures that are automatically generated with matplotlib, you HAVE to assign the result of mre.OutputHandler() to a variable. Otherwise, the created figures are not retained and vanish instantly.

Variables:

Example

import numpy as np
import matplotlib.pyplot as plt
import mrestimator as mre

bp  = mre.simulate_branching(numtrials=15)
rk1 = mre.coefficients(bp, method='trialseparated',
    desc='T')
rk2 = mre.coefficients(bp, method='stationarymean',
    desc='S')

m1 = mre.fit(rk1)
m2 = mre.fit(rk2)

# create a new handler by passing with list of elements
out = mre.OutputHandler([rk1, m1])

# manually add elements
out.add_coefficients(rk2)
out.add_fit(m2)

# save the plot and meta to disk
out.save('~/test')

Working with existing figures:

# create figure with subplots
fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)

# show each chart in its own subplot
mre.OutputHandler(rk1, ax1)
mre.OutputHandler(rk2, ax2)
mre.OutputHandler(m1, ax3)
mre.OutputHandler(m2, ax4)

# matplotlib customisations
myaxes = [ax1, ax2, ax3, ax4]
for ax in myaxes:
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)

plt.show(block=False)

# hide a legend
ax1.legend().set_visible(False)
plt.draw()
__init__(data=None, ax=None)[source]

Construct a new OutputHandler, optionally you can provide the a list of elements to plot.

ToDo: Make the OutputHandler talk to each other so that when one is written (possibly linked to others via one figure) all subfigure meta data is exported, too.

Parameters:
  • data (list, CoefficientResult or FitResult, optional) – List of the elements to plot/export. Can be added later.
  • ax (Axes, optional) – The an instance of a matplotlib axes (a subplot) to plot into.
add_coefficients(data, **kwargs)[source]

Add an individual CoefficientResult. Note that it is not possible to add the same data twice, instead it will be redrawn with the new arguments/style options provided.

Parameters:
  • data (CoefficientResult) – Added to the list of plotted elements.
  • kwargs – Keyword arguments passed to matplotlib.axes.Axes.plot. Use to customise the plots. If a label is set via kwargs, it will be used to overwrite the description of data in the meta file. If an alpha value is or linestyle is set, the shaded error region will be omitted.

Example

rk = mre.coefficients(mre.simulate_branching())

mout = mre.OutputHandler()
mout.add_coefficients(rk, color='C1', label='test')
add_fit(data, **kwargs)[source]

Add an individual FitResult. By default, the part of the fit that contributed to the fitting is drawn solid, the remaining range is dashed. Note that it is not possible to add the same data twice, instead it will be redrawn with the new arguments/style options provided.

Parameters:
  • data (FitResult) – Added to the list of plotted elements.
  • kwargs – Keyword arguments passed to matplotlib.axes.Axes.plot. Use to customise the plots. If a label is set via kwargs, it will be added as a note in the meta data. If linestyle is set, the dashed plot of the region not contributing to the fit is omitted.
add_ts(data, **kwargs)[source]

Add timeseries (possibly with trial structure). Not compatible with OutputHandlers that have data added via add_fit() or add_coefficients().

Parameters:
  • data (ndarray) – The timeseries to plot. If the ndarray is two dimensional, a trial structure is assumed and all trials are plotted using the same style (default or defined via kwargs). Not implemented yet: Providing a ts with its own custom axis
  • kwargs – Keyword arguments passed to matplotlib.axes.Axes.plot. Use to customise the plots.

Example

bp = mre.simulate_branching(numtrials=10)

tsout = mre.OutputHandler()
tsout.add_ts(bp, alpha=0.1, label='Trials')
tsout.add_ts(np.mean(bp, axis=0), label='Mean')

plt.show()
save(fname='', ftype='pdf', dpi=300)[source]

Saves plots (ax element of this handler) and source that it was created from to the specified location.

Parameters:fname (str, optional) – Path where to save, without file extension. Defaults to “./mre”
save_meta(fname='')[source]

Saves only the details/source used to create the plot. It is recommended to call this manually, if you decide to save the plots yourself or when you want only the fit results.

Parameters:fname (str, optional) – Path where to save, without file extension. Defaults to “./mre”
save_plot(fname='', ftype='pdf', dpi=300)[source]

Only saves plots (ignoring the source) to the specified location.

Parameters:
  • fname (str, optional) – Path where to save, without file extension. Defaults to “./mre”
  • ftype (str, optional) – So far, only ‘pdf’ and ‘png’ are implemented.
set_xdata(data=None, dt=1, dtunit=None)[source]

Adjust xdata of the plot, matching the input value. Returns an array of indices matching the incoming indices to already present ones. Automatically called when adding content.

If you want to customize the plot range, add all the content and use matplotlibs set_xlim function once at the end. (set_xdata() also manages meta data and can only increase the plot range)

Parameters:
  • data (array) – x-values to plot the fits for. data does not need to be spaced equally but is assumed to be sorted.
  • dt (float) – check if existing data can be mapped to the new, provided dt or the other way around. set_xdata() pads undefined areas with nan.
  • dtunit (str) – check if the new dtunit matches the one set previously. Any padding to match dt is only done if dtunits are the same, otherwise the plot falls back to using generic integer steps.
Returns:

array – containing the indices where the data given to this function coincides with (possibly) already existing data that was added/plotted before.

Example

out = mre.OutputHandler()

# 100 intervals of 2ms
out.set_xdata(np.arange(0,100), dt=2, dtunit='ms')

# increase resolution to 1ms for the first 50ms
# this changes the existing structure in the meta data. also
# the axis of `out` is not equally spaced anymore
fiftyms = np.arange(0,50)
out.set_xdata(fiftyms, dt=1, dtunit='ms')

# data with larger intervals is less dense, the returned list
# tells you which index in `out` belongs to every index
# in `xdat`
xdat = np.arange(0,50)
ydat = np.random_sample(50)
inds = out.set_xdata(xdat, dt=4, dtunit='ms')

# to pad `ydat` to match the axis of `out`:
temp = np.full(out.xdata.size, np.nan)
temp[inds] = ydat