Visualization

Visualization tools are included in prog_models.visualize, described below:

prog_models.visualize.display_labels(nrows, ncols, subplot_num, ax, opt, series_names)

Display label option for time series plot

Parameters
  • nrows (int) – number of subplot rows in plot

  • ncols (int) – number of subplot columns in plot

  • subplot_num (int) – subplot number

  • ax (matplotlib axis object) – current axis

  • opt (dict) –

    display options for the plot. Minimum options to be included are:

    1. ’display_labels’ = ‘minimal’ or ‘all’. if ‘minimal’, only the minimum number of axis ticks and labels are displayed according to the number of subplots. If ‘all’, then all x-ticks, x-labels, y-ticks, and y-labels will be displayed for each subplot.

    2. ’xlabel’ and ‘ylabel’. strings containing the xlabels and ylabels to display.

  • series_names (list of strings) – names of the time series

Example

nrows, ncols = 2, 1
subplot_num = 0
fig = plt.figure()
ax = fig.add_subplot(nrows, ncols, subplot_num+1)
opt = {‘xlabel’: ‘time’, ‘ylabel’: ‘state’, ‘display_labels’: ‘all’}
series_names= [‘x’, ‘v’]
display_labels(nrows, ncols, subplot_num, ax, opt, series_names)
prog_models.visualize.extract_option(opt, idx, series_names)

Extract option from either dictionary or list of plot options. The function takes the option “opt” and returns the option at index “idx” if opt is a list, the option corresponding to the series name at index idx, “series_names[idx]” if opt is a dictionary, or return the option “opt” if opt is neither a dictionary or a list.

Parameters
  • opt (dictionary of strings) – dictionary of label name) corresponding to entries in series_names, list of strings corresponding to the series names (in order), or a simple string

  • idx (int) – index of the option to extract in label options if opt is a string, or index of the corresponding series_names to extract if opt is a dictionary

  • series_names (list of strings) – series names used if opt is a dictionary

Returns

option – option corresponding to the index idx (if opt is a list of strings), corresponding to the series_names[idx] if opt is dictionary, or simply return opt if neither of those

Return type

string

Examples

Example 1:
………..
opt = {‘ylabel’: {‘x’: ‘position’, ‘v’: ‘velocity}}
series_names = [‘x’, ‘v’]
print(extract_option(opt[‘ylabel’], 0, series_names)) # ‘position’
print(extract_option(opt[‘ylabel’], 1, series_names)) # ‘velocity’

Example 2:
……….
opt = {‘ylabel’: [‘state value 1’, ‘state value 2’] }
print(extract_option(opt[‘ylabel’], 0, series_names)) # ‘state value 1’, please note that series_names is ignored
print(extract_option(opt[‘ylabel’], 1, series_names)) # ‘state value 2’

Example 3:
……….
opt = {‘ylabel’: ‘state output’}
series_names = [‘x’, ‘v’]
print(extract_option(opt[‘ylabel’], 0, series_names)) # ‘state output’, please note that idx and series_names are ignored
print(extract_option(opt[‘ylabel’], 1, {})) # ‘state output’, please note that idx and series_names are ignored
print(extract_option(opt[‘ylabel’], np.inf, [])) # ‘state output’, please note that idx and series_names are ignored
prog_models.visualize.get_subplot_dim(num_subplots, rowfirst=True)

Compute the number of rows and columns (nrows, ncols) for a figure with multiple subplots. The function returns number of rows and columns given num_subplots. Those numbers are computed sequentially until nrows * ncols >= num_subplots. By default, the function adds a new row first if the number of subplots has not been reached, then adds a new column. By passing rowfirst=False, the function will add a new column first if the number of subplot has not been reached, then a new row.

nrows and ncols are initialized to 1. If num_subplots==1, then subplots are not needed, and the function returns nrows=ncols=1. The command fig.add_subplot(nrows,ncols,1) generates a normal plot (no subplots).

Parameters
  • num_subplots (int) – number of subplots the figure should contain

  • rowfirst (Boolean) – whether to add a new row first or a new column first to increase the number of rows and columns if necessary. Default is rowfirst=True.

Returns

  • nrows (int) – number of subplots along the rows (vertical axis) of the figure

  • ncols (int) – number of subplots along the columns (horizontal axis) of the figure

Example

states = np.random.randn(1000,5) # let us consider a state vector with 5 dimensions, and 1000 values of the states (one for each time step)
n_states = states.shape[-1] # get the number of states (5)
print(get_subplot_dim(n_states)) # 3, 2
print(get_subplot_dim(n_states, rowfirst=False)) # 2, 3

fig = plt.figure()
ax = fig.add_subplot(nrows, ncols, 0)
# …
prog_models.visualize.plot_timeseries(t, s, legend=None, options=None)

Plot time series ‘s’ parametrized by time ‘t’. The function plot time series (in a single plot or subplots) contained in the array of dictionary s, produced by a prognostic model.

Input legend, and options are optional (default is None). If provided, they must be dictionaries with options for legend, and plot options, respectively.

The function is capable of plotting time series in a single plot (options[‘compact’]=True), or in multiple subplots in the same figure (options[‘compact’]=False). Legends can be displayed in each subplot or only one subplot, and names of time series, axis labels, plot title, legend titles and other are all customizable. Please read the help of the other functions suggested below for more info.

Parameters
  • t (list of floats) – time vector

  • s (array of dictionaries) –

    Each entry of the array is a dictionary with all time series, and one value per time series (corresponding to the time instant).

    Example: s = [ {‘x’: 0.0, ‘v’: 1.0},

    {‘x’: 1.0, ‘v’: 0.9},

    {‘x’: 1.83, ‘v’: 0.75},…]

  • legend (dict) – dict of legend options. See ‘set_legend’ function for more details

  • options (dict) – dict of plot options. See ‘set_plot_options’ function and other functions therein for more details

Returns

fig – object corresponding to the generated figure.

Return type

matplotlib figure object

Example

See new model example

prog_models.visualize.set_ax_options(ax, opts)

Set label options for plot axis.

The function set a number of labels defined in dictionary “opts” for the current axis “ax”.

At the moment, the options that can be set are:

title, title_fontsize, xlabel, ylabel, xticks, xtick_rotation, xtick_fontsize, tticks, ytick_rotation, ytick_fontsize

Input options are not mandatory, so only a subset of them can be defined.

Parameters
  • ax (matplotlib axis object) – matplotlib axis to visualize in figure

  • opts (dict) – display options for the axis / subplot. Available: title, title_fontsize, xlabel, ylabel, xticks, xtick_rotation, xtick_fontsize, tticks, ytick_rotation, ytick_fontsize

Example

opts = {‘title’: ‘this is a test title’,
‘title_fontsize’: 16, ‘xlabel’: ‘time’, ‘ylabel’: ‘state value’,
‘xtick_rotation’: 45, ‘xtick_fontsize’: 14, ‘ytick_rotation’: 0, ‘ytick_fontsize’: 14}
fig = plt.figure()
ax = fig.add_subplot(111)
set_ax_options(ax, opts)
prog_models.visualize.set_labels(ax, opt, series_names, axis='all')

Set labels of axis “ax” according to figure options “opt” and the time series names “series_names.” The function can set both x and y axis when input axis==’all’ (default), or rather set only x or y axis (axis=’x’ or axis=’y’, respectively).

Parameters
  • ax (matplotlib axis object) – axis to add labels and tick options to

  • opt (dictionary of label options) – options must include labels and ticks for both x and y axes; ‘xlabel’, ‘xticks’, ‘ylabel’, ‘yticks’ if ‘xticks’ is not empty (or None), then options can include also ‘xtick_rotation’, to rotate the axis ticks w.r.t. the plot, as well as ‘xtick_fontsize’, to change tick fontsize. the same applies to ‘yticks’.

  • series_names (list of strings) – name of time series

  • axis (string to decide which axis to display the options on.) – options are: ‘x’, ‘y’, or ‘all’ for both x and y

Example

fig = plt.figure()
ax = fig.add_subplot(221)
series_names = [‘x’, ‘y’]
opt = {‘xlabel’: ‘time’, ‘ylabel’: ‘state value’, ‘xticks’: [‘-pi’, ‘0’, ‘pi’], ‘xtick_fontsize’, 12, ‘xtick_rotation’, 90,
‘yticks’: [‘-pi’, ‘0’, ‘pi’], ‘ytick_fontsize’, 12, ‘ytick_rotation’, -90}
set_labels(ax, opt, series_names, axis=’all’)
prog_models.visualize.set_legend(ax, item, s_names, leg_opt)

Set legend for axis ‘ax’ for the ‘item-th’ time series entry. All time series labels are defined in ‘s_names’. For a comprehensive explanation of all legend options, see the Matplotlib guide on their website.

Parameters
  • ax (matplotlib axis object) –

  • item (int, index of the time series to be displayed in the legend) –

  • s_names (list of strings, names of all time series in the plot or subplot) –

  • leg_opt (dictionary containing all legend options necessary to place and modify the legend. Dictionary entries can be:) –

    • ‘bbox_to_anchor’ (tuple, coordinates of the legend location),

    • ’ncol’ (int, number of columns of the legend),

    • ’fontsize’ (int, legend font size),

    • ’fancybox’ (Boolean, Use a fancybox for the legend, True or False),

    • ’shadow’ (Boolean, Whether the legend box should have a shadow, True or False)

    • ’facecolor’ (string with color code, background color of the legend box),

    • ’edgecolor’ (string with color code, edge color of the legend box),

    • ’title’ (string, legend title)

Returns

ax – axis object with legend

Return type

axis object

Example

s_names = list(s.keys())
ax = fig.add_subplot()
ax.plot(t, [list(s_i.values()) for s_i in s])

leg_opt = {}
leg_opt[‘labels’] = s_names
leg_opt[‘loc’] = ‘best’
leg_opt[‘bbox_to_anchor’] = None
leg_opt[‘ncol’] = 1
leg_opt[‘fontsize’] = ‘x-large’
leg_opt[‘shadow’] = False
leg_opt[‘fancybox’] = False
leg_opt[‘framealpha’] = 1.0
leg_opt[‘facecolor’] = ‘w’
leg_opt[‘edgecolor’] = ‘w’
leg_opt[‘title’] = None

ax.legend(series_names, bbox_to_anchor=legend_options[‘bbox_to_anchor’],
ncol=legend_options[‘ncol’], fontsize=legend_options[‘fontsize’],
fancybox=legend_options[‘fancybox’], shadow=legend_options[‘shadow’],
framealpha=legend_options[‘framealpha’], facecolor=legend_options[‘facecolor’],
edgecolor=legend_options[‘edgecolor’], title=legend_options[‘title’])
prog_models.visualize.set_legend_options(leg_opt, s_names)

Set all remaining legend options given the legend options already specified by the users “leg_opt”, and the names of the time series in the plot “s_names.”

The visualize library works with specific values for some legend options. if those are not specified by the users, this function assign them their default values.

Parameters
  • leg_opt (dictionary of entries for the legend specified by the user.) –

  • s_names (list of strings, names of the time series in the current plot, whose names should appear in the legend.) –

Returns

leg_opt – dictionary of enetries for the legend.

Return type

dict

Example

s_names = [‘x’, ‘v’]
leg_opt = {‘display’: True, ‘labels’: None, ‘loc’=’best’, ‘fontsize’, 14}
leg_opt = set_legend_options(leg_opt, s_names)
print(leg_opt[‘labels’]) # [‘x’, ‘v’]
print(leg_opt[‘fancybox’]) # False
print(leg_opt[‘facecolor’]) # ‘w’
prog_models.visualize.set_plot_options(opt)

Set default plot options by integrating the options specified by the user in ‘opt’ The visualize library works with specific values to generate the plots. if those are not specified by the users, this function assign them their default values.

Parameters

opt (dictionary of plot options. Acceptable entries are:) –

  • ‘figsize’ : tuple of 2 floats, width and height of the figure

  • ’compact’ : Boolean, whether to plot a “compact” figure. If compact, all time series are displayed in one plot (multiple colored lines)

  • ’xlabel’ : string, label for the x-axis. Default is ‘time’

  • ’ylabel’ : string, label for the y-axis. Default is ‘state’

  • ’title’ : string or empty list or None, plot title. Default is empty list (no title)

  • ’title_fontsize’ : string or float, plot title fontsixe. Default is ‘x-large’

  • ’suptitle’ : string or empty list or None, plot suptitle. Default is empty list (no suptitle)

  • ’ticklabel_fontsize’ : string or float, tick label font sizes. Defaullt is ‘small’

  • ’tight_layout’ : Boolean, whether to use tight layout (minimize figure blank space around the graph)

  • ’display_labels’ : string, whether to display x and y-labels in the figure.

Returns

opt – dict of plot options with default values added.

Return type

dict

Example

opt = {}
opt = set_plot_options(opt)
print(opt) # opt[‘figsize’] = (10, 9), opt[‘compact’] = True, opt[‘xlabel’] = ‘time’, ….
prog_models.visualize.set_savefig_options(sfo)

Set all remaining save figure options given the options already specified by the user “sfo”.

Parameters

sfo (dictionary of options to save the current figure) –

if not provided, a figure will not be saved by default. Otherwise, sfo should provide the following dictionary entries:

  • ’save’ (Boolean, whether to save the figure or not, True or False)

  • ’dpi’ (int, resolution of the figure in dots per inch)

  • ’filename’ (string, figure filename, including file type, e.g., .pdf or .png. Default is ‘timeseries_plot.pdf’)

Returns

sfo – dict of default save figure options.

Return type

dict

Example

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0, 1], [3, 4])
sfo = {‘save’: True} # a figure has to be saved, but no dpi nor filename for the figure has been specified in sfo
sfo = set_savefig_options(sfo)
print(sfo) # sfo = {‘save’: True, ‘dpi’: 300, ‘filename’: ‘timeseries_plot.pdf’}