matpopmod.plot¶
This module provides functions to plot various quantities associated to matrix population models, including:
The
life cycle
graph.The
eigenvalues
of the projection matrix.Trajectories, both
deterministic
andstochastic
.Genealogies
of individual-based simulations (coming in v0.2.0).Various
matrices
.
By default, each function of this module will create a new figure when
called. If you want to draw the life-cycle graph as a subplot of an existing
figure, you can do so by providing an existing matplolib Axes
with the
argument ax.
The matplotlib Axes
used to draw the figure will be returned.
This is useful if you want to combine plots or to if you want to customize
them beyond what is possible with the arguments of the functions; otherwise,
you can ignore it.
Note that, unless you are in a Jupyter / IPython notebook, after
calling a plotting function you need to call either show()
or
savefig()
to show (resp. save) the figure that was produced.
Matplotlib aliases
Below are aliases of a few matplotlib functions, for convenience.
- matpopmod.plot.show()¶
Alias of
matplotlib.pyplot.show()
, to display the current figure.
- matpopmod.plot.savefig()¶
Alias of
matplotlib.pyplot.savefig()
, to save the current figure.
Plotting functions
- matpopmod.plot.life_cycle(model, node_labels='auto', edge_labels='{:.2f}', fertilities='C3-', survival='k-', mixed='C4-', node_colors='k', fill_nodes=False, node_size=0.7, node_fontsize='adaptive', show_legend=False, title=None, ax=None)¶
Plots the life-cycle graph of the
MPM
model. The following options are available for customization:node_labels
The labels to use for the classes, using one of the following:
None
or"none"
— do not display any label."numbers"
— use the indices of the classes."auto"
(default) — determine the labels automatically from the"Classes"
(or"MatrixClassAuthor"
) field ofmodel.metadata
. If neither of those fields exists, numbers will be used.custom — the list of labels to use. If every label contains a semicolon, then only the parts that precede those semicolons will be used as labels; the rest will be used in the legend. Otherwise, the whole entries will be used as labels and there will be no legend.
edges_labels
The format of the weight of the edges, as a Python format string. The default,
"{:.2f}"
, stands for floating point with two decimals. IfNone
is given, then the edges will not be labeled. Trailing zeros are removed for multiples of ten.fertilities
The line color and style to use for fertilities, either as a matplotlib format string or, for more control, as a dictionary of arguments. For instance,
"r--"
is equivalent to{"color" : "r", "linestyle": "--"}
and stands for “red dashed”. Defaults to solid red.survival
The line color and style to use for survival transitions. Defaults to solid black.
mixed
The line color and style for mixed (= survival or fertility) transitions. Default to solid purple.
node_colors
List of colors to use for each node. If a single value is given, it will be applied to all nodes. Defaults to black.
fill_nodes
List of booleans indicating whether each node should be filled. If a single boolean is given, it will be used for every node.
size
The size of nodes, in inches. Defaults to 0.7. Use None to determine it based on matplotlib’s default figure size.
node_fontsize
The font size for the labels of the classes, in points. Defaults to 16 if every label is one-letter long and 14 if at least one label is longer.
show_legend
Whether to display a legend giving the full name of the classes. The model needs to have appropriate metadata for this. Optionally, the vertical alignment of the legend can be specified by using one of “top”, “bottom” or “center”.
title
The title of the plot.
Here is an example that uses the default configuration:
import matpopmod as mpm mpm.plot.life_cycle(mpm.examples.dipsacus_sylvestris)
And here is an example that uses a custom one:
mpm.plot.life_cycle( mpm.examples.dipsacus_sylvestris, node_labels = [ "$S_1$: first year dormant seeds", "$S_2$: second year dormant seeds", "$R_1$: small rosettes", "$R_2$: medium rosettes", "$R_3$: large rosettes", "$F $: flowering plant"], show_legend = "center", fertilities = ":", node_colors = [ "#606060", "#606060", "#A9A9A9", "#A9A9A9", "#A9A9A9", "#E8E8E8"], fill_nodes = True, node_fontsize = 14, title = "Life cycle of $Dipsacus$ $sylvestris$" )
- matpopmod.plot.eigenvalues(model, log=False, grid_slices=16, grid_circles=4, grid_radius='auto', style_eig=None, style_grid=None, title=None, ax=None)¶
Plots the eigenvalues of the projection matrix of model in the complex plane. Non-simple eigenvalues are annotated with their algebraic multiplicity.
log
Whether to use a logarithmic scale for the modulus in polar coordinates.
grid_slices
The number of “slices” of the polar grid. The default, 16, corresponds to slices of \(2\pi / 16 \, \mathrm{rad} = 22.5^\circ\).
grid_circles
The number of concentric circles of the polar grid.
grid_radius
The radius of the polar grid. The default,
"auto"
, is to use λ.style_eig
The dictionary of styling elements to use to plot the eigenvalues.
style_grid
The dictionary of styling elements to use for the polar grid.
title
The title of the plot.
import matpopmod as mpm mpm.plot.eigenvalues(mpm.examples.dipsacus_sylvestris)
And here are the same eigenvalues, but using a “log-polar” plot and a bit of customization:
mpm.plot.eigenvalues( mpm.examples.dipsacus_sylvestris, log = True, grid_radius = 3, grid_slices = 12, grid_circles = 5, style_eig = dict(color="C0", linewidth=1) )
- matpopmod.plot.trajectory(traj, log=False, second_order=False, rescale=False, show_classes=False, stacked=False, show_period=False, colors=None, plot_style=None, show_legend=None, title=None, ax=None)¶
Plots the trajectory traj. The following plotting options are available:
log
Whether to use a logarithmic scale for the y-axis. Not compatible with stacked. This will automatically fall back to using a “symlog” scale whenever the plot contains zero or negative values (as can happen with show_classes or second_order).
second_order
Whether to plot the second order of the population dynamics, that is,
\[\tilde{\mathbf{n}}(t) = \mathbf{n}(t) - \mathbf{v} \mathbf{n}(0) \lambda^t \mathbf{w} \, .\]This is useful, e.g, to study the transient regime.
rescale
Whether to divide the population size by \(\lambda^t\). If second_order is set, it will be divided by \(|\lambda_2|^t\) instead, where \(\lambda_2\) is the maximum modulus of the subdominant eigenvalues instead (see e.g.
damping_ratio
).This option can be used to illustrate the convergence to the steady regime (though the resulting plot will be less informative than the one obtained with second_order). Used in conjunction with second_order, it can be used to show the periodicity of the second-order oscillations.
show_classes
Whether to display the abundance of each class or only the total population size, and which classes to show:
False
— plot the total population size.True
or"all"
— plot the abundance of each class separately[i1, ..., ik]
— show classes \(i_1, \ldots, i_k\), where the classes are numbered from 0. It is possible to group classes. For instance,[0, [1, 3]]
will plot two curves: the number of individuals in class 0 and the number of individuals in class 1 or 3.
stacked
If show_classes, whether to display the abundance of each class as a separate curve or using a “stacked plot” (making it easier to track the total population size and the relative contributions of each class).
show_period
Whether to show the period of second-order oscillations, if it exists.
colors
The colors to use for the classes. Can be either a list of colors, combining any format known to matplotlib, as in
colors = ["r", "##3333CC", "C2", (0, 153, 51)]
or the name of a matplotlib color palette, such as
"tab10"
or"Paired"
. In addition to these, we provide two Seaborn color palettes:"muted"
and"deep"
. The default,None
, is to use"muted"
but let it be over-ridden by plot_style.For a more drastic relooking of the plot, see plot_style.
plot_style
If provided, the name of the style-sheet to use for the plot. We recommend trying out
"seaborn"
and"ggplot"
. Unless it isNone
, colors takes precedence over plot_style for the colors of the classes of the model.show_legend
Whether to display the name of each class on the plot. If so, the names given in the
"Classes"
(or, if absent,"MatrixClassAuthor"
) field of model.metadata will be used.Optionally, you can specify the position of the legend by using one of the string arguments supported by matplotlib’s loc parameter, e.g,
"upper right"
. Otherwise,"best"
will be used by default.title
The title of the plot.
For further customization of the plot (changing axis labels, etc), you can work directly on the returned matplotlib
Axes
object.Here are a few examples of the type of plots that can be obtained for a given trajectory. All of these plots corresponds to the same trajectory, namely:
dipsacus = matpopmod.examples.dipsacus_sylvestris traj = dipsacus.trajectory([0, 0, 0, 0, 0, 1], 20)
Click on a thumbnail to see the corresponding code.
- matpopmod.plot.multiple_trajectories(trajs, classes='all', log=False, center=False, rescale=False, second_order=False, alpha=0.1, traj_style='default', show_expectation=True, show_average=False, show_quantiles=False, quantiles=(10, 90), show_std=False, plot_style=None, title=None, ax=None)¶
Plots the trajectories contained in trajs, overlaying them. This is especially useful to show several realizations of stochastic trajectories, for instance:
orcas = mpm.examples.orcinus_orca trajs = orcas.stochastic_trajectories( n0=[10, 0, 0, 0], t_max=100, reps=1000, reproduction="bernoulli") mpm.plot.multiple_trajectories(trajs)
The following plotting options are available:
classes
The classes to plot, as a list of integers from 0 to n-1. The abundances of the classes will be summed: for instance,
[0, 1]
will plot the number of individuals that are in class 0 or 1. The default,"all"
, is to plot the total population size.log
Whether to use a logarithmic scale for the y-axis. A “symlog” scale will be used if one of the trajectories contains zeros or negative values.
center
Whether to subtract the expected value of each trajectory, so as to show only their stochastic component.
rescale
Whether to rescale the trajectories, see
trajectory()
.second_order
Whether to subtract the first-order term of each trajectory, see
trajectory()
.alpha
The opacity of each trajectory, between 0 and 1.
traj_style
The color and style of each trajectory, either as a matplotlib fmt string or, for more flexibility, as a dictionary of keyword arguments. Defaults to thin solid black lines.
show_expectation
Whether to show the expected value of the trajectories. Can only be used if all trajectories correspond to the same model. If
True
, a solid red line will be used. If a matplotlib fmt string or a dictionary, will be used to set the style and color of the curve.show_average
Whether to show the empirical average of the plotted trajectories. If
True
, a solid purple line will be used. Can be a matplotlib fmt string or a dictionary to set the style and color of the curve.show_quantiles
Whether to show the empirical quantiles of the plotted trajectories. If
True
, dashed red lines will be used. Can be a matplotlib fmt string or a dictionary to set the style and color of the curve.quantiles
If show_quantiles, which quantiles should be displayed, as a list of integers between 0 and 100. The default,
(10, 90)
, is to show the 10% and 90% quantiles.show_std
Whether to show the average +/- the empirical standard deviation of the plotted trajectories. If
True
, dotted red lines will be used. Can be a matplotlib fmt string or a dictionary to set the style and color of the curve.plot_style
If provided, the name of the style-sheet to use for the plot; see
trajectory()
.title
The title of the plot.
Here are a few examples of the type of plots that can be obtained for a given trajectory. The following plots correspond to the same set of random trajectories, namely:
import matpopmod as mpm dp = mpm.examples.dipsacus_sylvestris n0 = [0, 0, 0, 0, 0, 1] trajs = dp.stochastic_trajectories(n0, t_max=15, reps=1000)
Rescaled, linear scale.
Second order, log scale.
Centered, rescaled and log scale.
- matpopmod.plot.matrices(matrices, plot_type='bubbles', same_scale=False, class_labels=None, matrix_names=None, show_entries=False, colors=None, plot_style=None, title=None, ax=None)¶
Graphical representation non-negative matrices.
matrices
The list (or tuple) of matrices to plot. If a single matrix is to be plotted, it can be passed directly instead of as a one-element list. All matrices must be square, non-negative, and have the same dimensions.
plot_type
The type of plot:
"bars"
— the value of entries are represented by the heights of bars."bubbles"
— the value of entries are represented by the radius of circles."heatmap"
— the value of entries are represented by a color. Only one matrix can be displayed with this option.
same_scale
When plotting several matrices, whether to use the same scale for all matrices. This makes direct comparison between matrices possible, but can make patterns harder to see. The default is
False
.class_labels
The labels of the classes, as a list of strings. For models from COMPADRE/COMADRE, the
"MatrixClassAuthor"
of the modelmetadata
can be used. IfNone
, integers will be used.matrix_names
The names of the matrices plotted, as a list of strings. If
None
(the default), no legend will be shown.show_entries
Whether to display the numerical value of non-zero matrix entries.
colorsplot_styletitleSee the documentation of
trajectory()
.Here is a showcase of the different plotting styles:
Bubbles
Heatmap
Bars