Plot module#

Functions for plotting graphs and graph properties.

Content#

nngt.plot.Animation2d(source, multimeter[, …]) Class to plot the raster plot, firing-rate, and average trajectory in a 2D phase-space for a network activity.
nngt.plot.AnimationNetwork(source, network) Class to plot the raster plot, firing-rate, and space-embedded spiking activity (neurons on the graph representation flash when spiking) in time.
nngt.plot.betweenness_distribution(network) Plotting the betweenness distribution of a graph.
nngt.plot.compare_population_attributes(…) Compare node attributes between two sets of nodes.
nngt.plot.correlation_to_attribute(network, …) For each node plot the value of reference_attributes against each of the other_attributes to check for correlations.
nngt.plot.degree_distribution(network[, …]) Plotting the degree distribution of a graph.
nngt.plot.draw_network(network[, nsize, …]) Draw a given graph/network.
nngt.plot.edge_attributes_distribution(…) Return node attributes for a set of nodes.
nngt.plot.node_attributes_distribution(…) Return node attributes for a set of nodes.
nngt.plot.palette([numbers])

Details#

This modules provides the following features:

  • plotting the distribution of some attribute over the graph
  • basic graph plotting
  • animation of some recorded activity
class nngt.plot.Animation2d(source, multimeter, start=0.0, timewindow=None, trace=5.0, x='time', y='V_m', sort_neurons=None, network=None, interval=50, vector_field=False, **kwargs)[source]#

Bases: nngt.plot.animations._SpikeAnimator, matplotlib.animation.FuncAnimation

Class to plot the raster plot, firing-rate, and average trajectory in a 2D phase-space for a network activity.

Generate a SubplotAnimation instance to plot a network activity.

Parameters:
  • source (tuple) – NEST gid of the ``spike_detector``(s) which recorded the network.
  • multimeter (tuple) – NEST gid of the ``multimeter``(s) which recorded the network.
  • timewindow (double, optional (default: None)) – Time window which will be shown for the spikes and self.second.
  • trace (double, optional (default: 5.)) – Interval of time (ms) over which the data is overlayed in red.
  • x (str, optional (default: “time”)) – Name of the x-axis variable (must be either “time” or the name of a NEST recordable in the multimeter).
  • y (str, optional (default: “V_m”)) – Name of the y-axis variable (must be either “time” or the name of a NEST recordable in the multimeter).
  • vector_field (bool, optional (default: False)) – Whether the \(\dot{x}\) and \(\dot{y}\) arrows should be added to phase space. Requires additional ‘dotx’ and ‘doty’ arguments which are user defined functions to compute the derivatives of x and x in time. These functions take 3 parameters, which are x, y, and time_dependent, where the last parameter is a list of doubles associated to recordables from the neuron model (see example for details). These recordables must be declared in a time_dependent parameter.
  • sort_neurons (str or list, optional (default: None)) – Sort neurons using a topological property (“in-degree”, “out-degree”, “total-degree” or “betweenness”), an activity-related property (“firing_rate”, ‘B2’) or a user-defined list of sorted neuron ids. Sorting is performed by increasing value of the sort_neurons property from bottom to top inside each group.
  • **kwargs (dict, optional (default: {})) – Optional arguments such as ‘make_rate’, ‘num_xarrows’, ‘num_yarrows’, ‘dotx’, ‘doty’, ‘time_dependent’, ‘recordables’, ‘arrow_scale’.
new_frame_seq()#
new_saved_frame_seq()#
on_click(event)#
on_keyboard_press(kb_event)#
on_keyboard_release(kb_event)#
save(filename, writer=None, fps=None, dpi=None, codec=None, bitrate=None, extra_args=None, metadata=None, extra_anim=None, savefig_kwargs=None)#

Saves a movie file by drawing every frame.

Parameters:
  • filename (str) – The output filename, e.g., mymovie.mp4.
  • writer (MovieWriter or str, optional) – A MovieWriter instance to use or a key that identifies a class to use, such as ‘ffmpeg’. If None, defaults to :rc:`animation.writer`.
  • fps (number, optional) – Frames per second in the movie. Defaults to None, which will use the animation’s specified interval to set the frames per second.
  • dpi (number, optional) – Controls the dots per inch for the movie frames. This combined with the figure’s size in inches controls the size of the movie. If None, defaults to :rc:`savefig.dpi`.
  • codec (str, optional) – The video codec to be used. Not all codecs are supported by a given MovieWriter. If None, default to :rc:`animation.codec`.
  • bitrate (number, optional) – Specifies the number of bits used per second in the compressed movie, in kilobits per second. A higher number means a higher quality movie, but at the cost of increased file size. If None, defaults to :rc:`animation.bitrate`.
  • extra_args (list, optional) – List of extra string arguments to be passed to the underlying movie utility. If None, defaults to :rc:`animation.extra_args`.
  • metadata (Dict[str, str], optional) – Dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment.
  • extra_anim (list, optional) – Additional Animation objects that should be included in the saved movie file. These need to be from the same matplotlib.figure.Figure instance. Also, animation frames will just be simply combined, so there should be a 1:1 correspondence between the frames from the different animations.
  • savefig_kwargs (dict, optional) – Is a dictionary containing keyword arguments to be passed on to the savefig command which is called repeatedly to save the individual frames.

Notes

fps, codec, bitrate, extra_args, metadata are used to construct a MovieWriter instance and can only be passed if writer is a string. If they are passed as non-None and writer is a MovieWriter, a RuntimeError will be raised.

save_movie(filename, fps=30, video_encoder='html5', codec=None, bitrate=-1, start=None, stop=None, interval=None, num_frames=None, metadata=None)#

Save the animation to a movie file.

Parameters:
  • filename (str) – Name of the file where the movie will be saved.
  • fps (int, optional (default: 30)) – Frame per second.
  • video_encoder (str, optional (default ‘html5’)) – Movie encoding format; either ‘ffmpeg’, ‘html5’, or ‘imagemagick’.
  • codec (str, optional (default: None)) – Codec to use for writing movie; if None, default animation.codec from matplotlib will be used.
  • bitrate (int, optional (default: -1)) – Controls size/quality tradeoff for movie. Default (-1) lets utility auto-determine.
  • start (float, optional (default: initial time)) – Start time, corresponding to the first spike time that will appear on the video.
  • stop (float, optional (default: final time)) – Stop time, corresponding to the last spike time that will appear on the video.
  • interval (int, optional (default: None)) – Timestep increment for each new frame. Default saves all timesteps (often heavy). E.g. setting interval to 10 will make the file 10 times lighter.
  • num_frames (int, optional (default: None)) – Total number of frames that should be saved.
  • metadata (dict, optional (default: None)) – Metadata for the video (e.g. ‘title’, ‘artist’, ‘comment’, ‘copyright’)

Notes

  • ffmpeg is required for ‘ffmpeg’ and ‘html5’ encoders. To get available formats, type ffmpeg -formats in a terminal; type ffmpeg -codecs | grep EV for available codecs.
  • Imagemagick is required for ‘imagemagick’ encoder.
set_axis(axis, xlabel, ylabel, lines, xdata=None, ydata=None, **kwargs)#

Setup an axis.

Parameters:
  • axis (matplotlib.axes.Axes object)
  • xlabel (str)
  • ylabel (str)
  • lines (list of matplotlib.lines.Line2D objects)
  • xdata (1D array-like, optional (default: None))
  • ydata (1D array-like, optional (default: None))
  • **kwargs (dict, optional (default: {})) – Optional arguments (“xlim” or “ylim”, 2-tuples; “set_xticks”, bool).
steps = [1, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000, 10000, 25000, 50000, 75000, 100000, 250000]#
to_html5_video(embed_limit=None)#

Returns animation as an HTML5 video tag.

This saves the animation as an h264 video, encoded in base64 directly into the HTML5 video tag. This respects the rc parameters for the writer as well as the bitrate. This also makes use of the interval to control the speed, and uses the repeat parameter to decide whether to loop.

to_jshtml(fps=None, embed_frames=True, default_mode=None)#

Generate HTML representation of the animation

class nngt.plot.AnimationNetwork(source, network, resolution=1.0, start=0.0, timewindow=None, trace=5.0, show_spikes=False, sort_neurons=None, decimate_connections=False, interval=50, repeat=True, resting_size=None, active_size=None, **kwargs)[source]#

Bases: nngt.plot.animations._SpikeAnimator, matplotlib.animation.FuncAnimation

Class to plot the raster plot, firing-rate, and space-embedded spiking activity (neurons on the graph representation flash when spiking) in time.

Generate a SubplotAnimation instance to plot a network activity.

Parameters:
  • source (tuple) – NEST gid of the ``spike_detector``(s) which recorded the network.
  • network (SpatialNetwork) – Network embedded in space to plot the actvity of the neurons in space.
  • resolution (double, optional (default: None)) – Time resolution of the animation.
  • timewindow (double, optional (default: None)) – Time window which will be shown for the spikes and self.second.
  • trace (double, optional (default: 5.)) – Interval of time (ms) over which the data is overlayed in red.
  • show_spikes (bool, optional (default: True)) – Whether a spike trajectory should be displayed on the network.
  • sort_neurons (str or list, optional (default: None)) – Sort neurons using a topological property (“in-degree”, “out-degree”, “total-degree” or “betweenness”), an activity-related property (“firing_rate”, ‘B2’) or a user-defined list of sorted neuron ids. Sorting is performed by increasing value of the sort_neurons property from bottom to top inside each group.
  • **kwargs (dict, optional (default: {})) – Optional arguments such as ‘make_rate’, or all arguments for the nngt.plot.draw_network().
new_frame_seq()#
new_saved_frame_seq()#
on_click(event)#
on_keyboard_press(kb_event)#
on_keyboard_release(kb_event)#
save(filename, writer=None, fps=None, dpi=None, codec=None, bitrate=None, extra_args=None, metadata=None, extra_anim=None, savefig_kwargs=None)#

Saves a movie file by drawing every frame.

Parameters:
  • filename (str) – The output filename, e.g., mymovie.mp4.
  • writer (MovieWriter or str, optional) – A MovieWriter instance to use or a key that identifies a class to use, such as ‘ffmpeg’. If None, defaults to :rc:`animation.writer`.
  • fps (number, optional) – Frames per second in the movie. Defaults to None, which will use the animation’s specified interval to set the frames per second.
  • dpi (number, optional) – Controls the dots per inch for the movie frames. This combined with the figure’s size in inches controls the size of the movie. If None, defaults to :rc:`savefig.dpi`.
  • codec (str, optional) – The video codec to be used. Not all codecs are supported by a given MovieWriter. If None, default to :rc:`animation.codec`.
  • bitrate (number, optional) – Specifies the number of bits used per second in the compressed movie, in kilobits per second. A higher number means a higher quality movie, but at the cost of increased file size. If None, defaults to :rc:`animation.bitrate`.
  • extra_args (list, optional) – List of extra string arguments to be passed to the underlying movie utility. If None, defaults to :rc:`animation.extra_args`.
  • metadata (Dict[str, str], optional) – Dictionary of keys and values for metadata to include in the output file. Some keys that may be of use include: title, artist, genre, subject, copyright, srcform, comment.
  • extra_anim (list, optional) – Additional Animation objects that should be included in the saved movie file. These need to be from the same matplotlib.figure.Figure instance. Also, animation frames will just be simply combined, so there should be a 1:1 correspondence between the frames from the different animations.
  • savefig_kwargs (dict, optional) – Is a dictionary containing keyword arguments to be passed on to the savefig command which is called repeatedly to save the individual frames.

Notes

fps, codec, bitrate, extra_args, metadata are used to construct a MovieWriter instance and can only be passed if writer is a string. If they are passed as non-None and writer is a MovieWriter, a RuntimeError will be raised.

save_movie(filename, fps=30, video_encoder='html5', codec=None, bitrate=-1, start=None, stop=None, interval=None, num_frames=None, metadata=None)#

Save the animation to a movie file.

Parameters:
  • filename (str) – Name of the file where the movie will be saved.
  • fps (int, optional (default: 30)) – Frame per second.
  • video_encoder (str, optional (default ‘html5’)) – Movie encoding format; either ‘ffmpeg’, ‘html5’, or ‘imagemagick’.
  • codec (str, optional (default: None)) – Codec to use for writing movie; if None, default animation.codec from matplotlib will be used.
  • bitrate (int, optional (default: -1)) – Controls size/quality tradeoff for movie. Default (-1) lets utility auto-determine.
  • start (float, optional (default: initial time)) – Start time, corresponding to the first spike time that will appear on the video.
  • stop (float, optional (default: final time)) – Stop time, corresponding to the last spike time that will appear on the video.
  • interval (int, optional (default: None)) – Timestep increment for each new frame. Default saves all timesteps (often heavy). E.g. setting interval to 10 will make the file 10 times lighter.
  • num_frames (int, optional (default: None)) – Total number of frames that should be saved.
  • metadata (dict, optional (default: None)) – Metadata for the video (e.g. ‘title’, ‘artist’, ‘comment’, ‘copyright’)

Notes

  • ffmpeg is required for ‘ffmpeg’ and ‘html5’ encoders. To get available formats, type ffmpeg -formats in a terminal; type ffmpeg -codecs | grep EV for available codecs.
  • Imagemagick is required for ‘imagemagick’ encoder.
set_axis(axis, xlabel, ylabel, lines, xdata=None, ydata=None, **kwargs)#

Setup an axis.

Parameters:
  • axis (matplotlib.axes.Axes object)
  • xlabel (str)
  • ylabel (str)
  • lines (list of matplotlib.lines.Line2D objects)
  • xdata (1D array-like, optional (default: None))
  • ydata (1D array-like, optional (default: None))
  • **kwargs (dict, optional (default: {})) – Optional arguments (“xlim” or “ylim”, 2-tuples; “set_xticks”, bool).
steps = [1, 5, 10, 20, 25, 50, 100, 200, 250, 500, 1000, 2000, 2500, 5000, 10000, 25000, 50000, 75000, 100000, 250000]#
to_html5_video(embed_limit=None)#

Returns animation as an HTML5 video tag.

This saves the animation as an h264 video, encoded in base64 directly into the HTML5 video tag. This respects the rc parameters for the writer as well as the bitrate. This also makes use of the interval to control the speed, and uses the repeat parameter to decide whether to loop.

to_jshtml(fps=None, embed_frames=True, default_mode=None)#

Generate HTML representation of the animation

nngt.plot.draw_network(network, nsize='total-degree', ncolor='group', nshape='o', nborder_color='k', nborder_width=0.5, esize=1.0, ecolor='k', ealpha=0.5, max_nsize=5.0, max_esize=2.0, curved_edges=False, threshold=0.5, decimate=None, spatial=True, restrict_sources=None, restrict_targets=None, show_environment=True, fast=False, size=(600, 600), xlims=None, ylims=None, dpi=75, axis=None, colorbar=False, show=False, **kwargs)[source]#

Draw a given graph/network.

Parameters:
  • network (Graph or subclass) – The graph/network to plot.
  • nsize (float, array of float or string, optional (default: “total-degree”)) – Size of the nodes as a percentage of the canvas length. Otherwise, it can be a string that correlates the size to a node attribute among “in/out/total-degree”, or “betweenness”.
  • ncolor (float, array of floats or string, optional (default: 0.5)) – Color of the nodes; if a float in [0, 1], position of the color in the current palette, otherwise a string that correlates the color to a node attribute among “in/out/total-degree”, “betweenness” or “group”.
  • nshape (char or array of chars, optional (default: “o”)) – Shape of the nodes (see Matplotlib markers).
  • nborder_color (char, float or array, optional (default: “k”)) – Color of the node’s border using predefined Matplotlib colors). or floats in [0, 1] defining the position in the palette.
  • nborder_width (float or array of floats, optional (default: 0.5)) – Width of the border in percent of canvas size.
  • esize (float, str, or array of floats, optional (default: 0.5)) – Width of the edges in percent of canvas length. Available string values are “betweenness” and “weight”.
  • ecolor (str, char, float or array, optional (default: “k”)) – Edge color. If ecolor=”groups”, edges color will depend on the source and target groups, i.e. only edges from and toward same groups will have the same color.
  • max_esize (float, optional (default: 5.)) – If a custom property is entered as esize, this normalizes the edge width between 0. and max_esize.
  • decimate (int, optional (default: keep all connections)) – Plot only one connection every decimate. Use -1 to hide all edges.
  • spatial (bool, optional (default: True)) – If True, use the neurons’ positions to draw them.
  • restrict_sources (str or list, optional (default: all)) – Only draw edges starting from a restricted set of source nodes.
  • restrict_targets (str or list, optional (default: all)) – Only draw edges ending on a restricted set of target nodes.
  • show_environment (bool, optional (default: True)) – Plot the environment if the graph is spatial.
  • fast (bool, optional (default: False)) – Use a faster algorithm to plot the edges. This method leads to less pretty plots and zooming on the graph will make the edges start or ending in places that will differ more or less strongly from the actual node positions.
  • size (tuple of ints, optional (default: (600,600))) – (width, height) tuple for the canvas size (in px).
  • dpi (int, optional (default: 75)) – Resolution (dot per inch).
  • colorbar (bool, optional (default: False)) – Whether to display a colorbar for the node colors or not.
  • show (bool, optional (default: True)) – Display the plot immediately.
nngt.plot.palette(numbers=None)[source]#
nngt.plot.degree_distribution(network, deg_type='total', nodes=None, num_bins='doane', use_weights=False, logx=False, logy=False, axis=None, axis_num=None, colors=None, norm=False, show=False, title=None, **kwargs)[source]#

Plotting the degree distribution of a graph.

Parameters:
  • graph (Graph or subclass) – The graph to analyze.
  • deg_type (string or N-tuple, optional (default: “total”)) – Type of degree to consider (“in”, “out”, or “total”)
  • nodes (list or numpy.array of ints, optional (default: all nodes)) – Restrict the distribution to a set of nodes.
  • num_bins (int or N-tuple, optional (default: ‘auto’):) – Number of bins used to sample the distribution. Defaults to unsupervised Bayesian blocks method.
  • use_weights (bool, optional (default: False)) – Use weighted degrees (do not take the sign into account : only the magnitude of the weights is considered).
  • logx (bool, optional (default: False)) – Use log-spaced bins.
  • logy (bool, optional (default: False)) – Use logscale for the degree count.
  • axis (matplotlib.axes.Axes instance, optional (default: new one)) – Axis which should be used to plot the histogram, if None, a new one is created.
  • show (bool, optional (default: True)) – Show the Figure right away if True, else keep it warm for later use.
  • **kwargs (keyword arguments for matplotlib.axes.Axes.bar().)
nngt.plot.betweenness_distribution(network, btype='both', use_weights=True, nodes=None, logx=False, logy=False, num_nbins='auto', num_ebins=None, axes=None, colors=None, norm=False, show=True, **kwargs)[source]#

Plotting the betweenness distribution of a graph.

Parameters:
  • graph (Graph or subclass) – the graph to analyze.
  • btype (string, optional (default: “both”)) – type of betweenness to display (“node”, “edge” or “both”)
  • use_weights (bool, optional (default: True)) – use weighted degrees (do not take the sign into account : all weights are positive).
  • nodes (list or numpy.array of ints, optional (default: all nodes)) – Restrict the distribution to a set of nodes (taken into account only for the node attribute).
  • logx (bool, optional (default: False)) – use log-spaced bins.
  • logy (bool, optional (default: False)) – use logscale for the degree count.
  • num_nbins (int or ‘auto’, optional (default: ‘auto’):) – Number of bins used to sample the node distribution. Defaults to unsupervised Bayesian blocks method.
  • num_ebins (int or ‘auto’, optional (default: None):) – Number of bins used to sample the edge distribution. Defaults to max(num_edges / 500., 10) (‘auto’ method will be slow).
  • axes (list of matplotlib.axis.Axis, optional (default: new ones)) – Axes which should be used to plot the histogram, if None, new ones are created.
  • show (bool, optional (default: True)) – Show the Figure right away if True, else keep it warm for later use.
nngt.plot.edge_attributes_distribution(network, attributes, edges=None, num_bins='auto', logx=False, logy=False, norm=False, title=None, colors=None, show=True, **kwargs)[source]#

Return node attributes for a set of nodes.

New in version 1.0.3.

Parameters:
  • network (Graph) – The graph where the nodes belong.
  • attributes (str or list) – Attributes which should be returned (e.g. “betweenness”, “delay”, “weights”).
  • edges (list, optional (default: all edges)) – Edges for which the attributes should be returned.
  • num_bins (int or list, optional (default: ‘auto’)) – Number of bins to plot the distributions. If only one int is provided, it is used for all attributes, otherwise a list containing one int per attribute in attributes is required. Defaults to unsupervised Bayesian blocks method.
  • logx (bool or list, optional (default: False)) – Use log-spaced bins.
  • logy (bool or list, optional (default: False)) – use logscale for the node count.
nngt.plot.node_attributes_distribution(network, attributes, nodes=None, num_bins='auto', logx=False, logy=False, norm=False, title=None, colors=None, show=True, **kwargs)[source]#

Return node attributes for a set of nodes.

Parameters:
  • network (Graph) – The graph where the nodes belong.
  • attributes (str or list) – Attributes which should be returned, among: * “betweenness” * “clustering” * “closeness” * “in-degree”, “out-degree”, “total-degree” * “subgraph_centrality” * “b2” (requires NEST) * “firing_rate” (requires NEST)
  • nodes (list, optional (default: all nodes)) – Nodes for which the attributes should be returned.
  • num_bins (int or list, optional (default: ‘auto’)) – Number of bins to plot the distributions. If only one int is provided, it is used for all attributes, otherwise a list containing one int per attribute in attributes is required. Defaults to unsupervised Bayesian blocks method.
  • logx (bool or list, optional (default: False)) – Use log-spaced bins.
  • logy (bool or list, optional (default: False)) – use logscale for the node count.
nngt.plot.compare_population_attributes(network, attributes, nodes=None, reference_nodes=None, num_bins='auto', reference_color='gray', title=None, logx=False, logy=False, show=True, **kwargs)[source]#

Compare node attributes between two sets of nodes. Since number of nodes can vary, normalized distributions are used.

Parameters:
  • network (Graph) – The graph where the nodes belong.
  • attributes (str or list) – Attributes which should be returned, among: * “betweenness” * “clustering” * “in-degree”, “out-degree”, “total-degree” * “subgraph_centrality” * “b2” (requires NEST) * “firing_rate” (requires NEST)
  • nodes (list, optional (default: all nodes)) – Nodes for which the attributes should be returned.
  • reference_nodes (list, optional (default: all nodes)) – Reference nodes for which the attributes should be returned in order to compare with nodes.
  • num_bins (int or list, optional (default: ‘auto’)) – Number of bins to plot the distributions. If only one int is provided, it is used for all attributes, otherwize a list containing one int per attribute in attributes is required. Defaults to unsupervised Bayesian blocks method.
  • logx (bool or list, optional (default: False)) – Use log-spaced bins.
  • logy (bool or list, optional (default: False)) – use logscale for the node count.
nngt.plot.correlation_to_attribute(network, reference_attribute, other_attributes, nodes=None, title=None, show=True)[source]#

For each node plot the value of reference_attributes against each of the other_attributes to check for correlations.

Parameters:
  • network (Graph) – The graph where the nodes belong.
  • reference_attribute (str or array-like) – Attribute which should serve as reference, among:
    • “betweenness”
    • “clustering”
    • “in-degree”, “out-degree”, “total-degree”
    • “subgraph_centrality”
    • “b2” (requires NEST)
    • “firing_rate” (requires NEST)
    • a custom array of values, in which case one entry per node in nodes is required.
  • other_attributes (str or list) – Attributes that will be compared to the reference.
  • nodes (list, optional (default: all nodes)) – Nodes for which the attributes should be returned.