Note

This is the documentation for the current state of the development branch of Qiskit Experiments. The documentation or APIs here can change prior to being released.

BaseDrawer

class BaseDrawer[source]

Abstract class for the serializable Qiskit Experiments figure drawer.

Overview

A drawer may be implemented by different drawer backends such as matplotlib or Plotly. Sub-classes that wrap these backends by subclassing BaseDrawer must implement the following abstract methods.

initialize_canvas

This method should implement a protocol to initialize a drawer canvas with user input axis object. Note that drawer supports visualization of experiment results in multiple canvases tiled into N (row) x M (column) inset grids, which is specified in the option subplots. By default, this is N=1, M=1 and thus no inset grid will be initialized.

This method should first check the drawer options (options) for the axis object and initialize the axis only when it is not provided by the options. Once axis is initialized, this is set to the instance member self._axis.

format_canvas

This method formats the appearance of the canvas. Typically, it updates axis and tick labels. Note that the axis SI unit may be specified in the drawer figure_options. In this case, axis numbers should be auto-scaled with the unit prefix.

Drawing Methods

scatter

This method draws scatter points on the canvas, like a scatter-plot, with optional error-bars in both the X and Y axes.

line

This method plots a line from provided X and Y values.

filled_y_area

This method plots a shaped region bounded by upper and lower Y-values. This method is typically called with interpolated x and a pair of y values that represent the upper and lower bound within certain confidence interval. If this is called multiple times, it may be necessary to set the transparency so that overlapping regions can be distinguished.

filled_x_area

This method plots a shaped region bounded by upper and lower X-values, as a function of Y-values. This method is a rotated analogue of filled_y_area().

textbox

This method draws a text-box on the canvas, which is a rectangular region containing some text.

Legends

Legends are generated based off of drawn graphics and their labels or names. These are managed by individual drawer subclasses, and generated when the format_canvas() method is called. Legend entries are created when any drawing function is called with legend=True. There are three parameters in drawing functions that are relevant to legend generation: name, label, and legend. If a user would like the graphics drawn onto a canvas to be used as the graphical component of a legend entry; they should set legend=True. The legend entry label can be defined in three locations: the label parameter of drawing functions, the "label" entry in series_params, and the name parameter of drawing functions. These three possible label variables have a search hierarchy given by the order in the aforementioned list. If one of the label variables is None, the next is used. If all are None, a legend entry is not generated for the given series.

The recommended way to customize the legend entries is as follows:

  1. Set the labels in the series_params option, keyed on the series names.

  2. Initialize the canvas.

  3. Call relevant drawing methods to create the figure. When calling the drawing method that creates the graphic you would like to use in the legend, set legend=True. For example, drawer.scatter(...,legend=True) would use the scatter points as the legend graphics for the given series.

  4. Format the canvas and call figure() to get the figure.

Options and Figure Options

Drawers have both options and figure_options available to set parameters that define how to draw and what is drawn, respectively. BasePlotter is similar in that it also has options and figure_options. The former contains class-specific variables that define how an instance behaves. The latter contains figure-specific variables that typically contain values that are drawn on the canvas, such as text. For details on the difference between the two sets of options, see the documentation for BasePlotter.

Note

If a drawer instance is used with a plotter, then there is the potential for any figure option to be overwritten with their value from the plotter. This means that the drawer instance would be modified indirectly when the BasePlotter.figure() method is called. This must be kept in mind when creating subclasses of BaseDrawer.

Options

The following can be set using set_options().

Options
  • Defined in the class BaseDrawer:

    • axis (Any)

      Default value: None
      Arbitrary object that can be used as a canvas.
    • subplots (Tuple[int, int])

      Default value: (1, 1)
      Number of rows and columns when the experimental result is drawn in the multiple windows.
    • default_style (PlotStyle)

      Default value: {"figsize": ("figsize", (8, 5)), "legend_loc": ("legend_loc", None), "tick_label_size": ("tick_label_size", 14), "axis_label_size": ("axis_label_size", 16), "textbox_rel_pos": ("textbox_rel_pos", (0.5, -0.25)), "textbox_text_size": ("textbox_text_size", 12), "errorbar_capsize": ("errorbar_capsize", 4), "symbol_size": ("symbol_size", 6.0)}
      The default style for drawer. This must contain all required style parameters for drawer, as is defined in PlotStyle.default_style(). Subclasses can add extra required style parameters by overriding _default_style().

Figure options

The following can be set using set_figure_options().

Options
  • Defined in the class BaseDrawer:

    • xlabel (Union[str, List[str]])

      Default value: None
      X-axis label string of the output figure. If there are multiple columns in the canvas, this could be a list of labels.
    • ylabel (Union[str, List[str]])

      Default value: None
      Y-axis label string of the output figure. If there are multiple rows in the canvas, this could be a list of labels.
    • xlim (Union[Tuple[float, float], List[Tuple[float, float]])

      Default value: None
      Min and max value of the horizontal axis. If not provided, it is automatically scaled based on the input data points. If there are multiple columns in the canvas, this could be a list of xlims.
    • ylim (Union[Tuple[float, float], List[Tuple[float, float]])

      Default value: None
      Min and max value of the vertical axis. If not provided, it is automatically scaled based on the input data points. If there are multiple rows in the canvas, this could be a list of ylims.
    • xval_unit (Union[str, List[str]])

      Default value: None
      Unit of x values. No scaling prefix is needed here as this is controlled by xval_unit_scale. If there are multiple columns in the canvas, this could be a list of xval_units.
    • yval_unit (Union[str, List[str]])

      Default value: None
      Unit of y values. No scaling prefix is needed here as this is controlled by yval_unit_scale. If there are multiple rows in the canvas, this could be a list of yval_units.
    • xval_unit_scale (Union[bool, List[bool]])

      Default value: True
      Whether to add an SI unit prefix to xval_unit if needed. For example, when the x values represent time and xval_unit="s", xval_unit_scale=True adds an SI unit prefix to "s" based on X values of plotted data. In the output figure, the prefix is automatically selected based on the maximum value in this axis. If your x values are in [1e-3, 1e-4], they are displayed as [1 ms, 10 ms]. By default, this option is set to True. If False is provided, the axis numbers will be displayed in the scientific notation. If there are multiple columns in the canvas, this could be a list of xval_unit_scale.
    • yval_unit_scale (Union[bool, List[bool]])

      Default value: True
      Whether to add an SI unit prefix to yval_unit if needed. See xval_unit_scale for details. If there are multiple rows in the canvas, this could be a list of yval_unit_scale.
    • xscale (str)

      Default value: None
      The scaling of the x-axis, such as log or linear.
    • yscale (str)

      Default value: None
      The scaling of the y-axis, such as log or linear.
    • figure_title (str)

      Default value: None
      Title of the figure. Defaults to None, i.e. nothing is shown.
    • sharex (bool)

      Default value: True
      Set True to share x-axis ticks among sub-plots.
    • sharey (bool)

      Default value: True
      Set True to share y-axis ticks among sub-plots.
    • series_params (Dict[str, Dict[str, Any]])

      Default value: {}
      A dictionary of parameters for each series. This is keyed on the name for each series. Sub-dictionary is expected to have the following three configurations, “canvas”, “color”, “symbol” and “label”; “canvas” is the integer index of axis (when multi-canvas plot is set), “color” is the color of the drawn graphics, “symbol” is the series marker style for scatter plots, and “label” is a user provided series label that appears in the legend.
    • custom_style (PlotStyle)

      Default value: {}
      The style definition to use when drawing. This overwrites style parameters in default_style in options. Defaults to an empty PlotStyle instance (i.e., PlotStyle()).

Initialization

Create a BaseDrawer instance.

Attributes

figure

Return figure object handler to be saved in the database.

figure_options

Return the figure options.

These are typically updated by a plotter instance, and thus may change. It is recommended to set figure options in a parent BasePlotter instance that contains the BaseDrawer instance.

options

Return the drawer options.

style

The combined plot style for this drawer.

The returned style instance is a combination of options.default_style and figure_options.custom_style. Style parameters set in custom_style override those set in default_style. If custom_style is not an instance of PlotStyle, the returned style is equivalent to default_style.

Returns:

The plot style for this drawer.

Methods

config()[source]

Return the config dictionary for this drawer.

Return type:

Dict

abstract filled_x_area(x_ub, x_lb, y_data, name=None, label=None, legend=False, **options)[source]

Draw filled area as a function of y-values.

Parameters:
  • x_ub (Sequence[float]) – The upper boundary of X values.

  • x_lb (Sequence[float]) – The lower boundary of X values.

  • y_data (Sequence[float]) – Y values.

  • name (str | int | float | None) – Name of this series.

  • label (str | None) – Optional legend label to override name and series_params.

  • legend (bool) – Whether the drawn area must have a legend entry. Defaults to False. The series label in the legend will be label if it is not None. If it is, then series_params is searched for a "label" entry for the series identified by name. If this is also None, then name is used as the fallback. If no name is provided, then no legend entry is generated.

  • options – Valid options for the drawer backend API.

abstract filled_y_area(x_data, y_ub, y_lb, name=None, label=None, legend=False, **options)[source]

Draw filled area as a function of x-values.

Parameters:
  • x_data (Sequence[float]) – X values.

  • y_ub (Sequence[float]) – The upper boundary of Y values.

  • y_lb (Sequence[float]) – The lower boundary of Y values.

  • name (str | int | float | None) – Name of this series.

  • label (str | None) – Optional legend label to override name and series_params.

  • legend (bool) – Whether the drawn area must have a legend entry. Defaults to False. The series label in the legend will be label if it is not None. If it is, then series_params is searched for a "label" entry for the series identified by name. If this is also None, then name is used as the fallback. If no name is provided, then no legend entry is generated.

  • options – Valid options for the drawer backend API.

abstract format_canvas()[source]

Final cleanup for the canvas appearance.

abstract hline(y_value, name=None, label=None, legend=False, **options)[source]

Draw a horizontal line.

Parameters:
  • y_value (float) – Y value for line.

  • name (str | int | float | None) – Name of this series.

  • label (str | None) – Optional legend label to override name and series_params.

  • legend (bool) – Whether the drawn area must have a legend entry. Defaults to False. The series label in the legend will be label if it is not None. If it is, then series_params is searched for a "label" entry for the series identified by name. If this is also None, then name is used as the fallback. If no name is provided, then no legend entry is generated.

  • options – Valid options for the drawer backend API.

abstract image(data, extent=None, name=None, label=None, cmap=None, cmap_use_series_colors=False, colorbar=False, **options)[source]

Draw an image of numerical values, series names, or RGB/A values.

Parameters:
  • data (ndarray) – The two-/three-dimensional data defining an image. If data.dims==2, then the pixel colors are determined by cmap and cmap_use_series_colors. If data.dims==3, then it is assumed that data contains either RGB or RGBA data; which requires the third dimension to have length 3 or 4 respectively. For RGB/A data, the elements of data must be floats or integers in the range 0-1 and 0-255 respectively. If the data is two-dimensional, there is no limit on the range of the values if they are numerical. If cmap_use_series_colors=True, then data contains series names; which can be strings or numerical values, as long as they are appropriate series names.

  • extent (Tuple[float, float, float, float] | None) – An optional tuple (x_min, x_max, y_min, y_max) which defines a rectangular region within which the values inside data should be plotted. The units of extent are the same as those of the X and Y axes for the axis. If None, the extent of the image is taken as (0, data.shape[0], 0, data.shape[1]). Default is None.

  • name (str | int | float | None) – Name of this image. Used to lookup canvas and label in series_params.

  • label (str | None) – An optional label for the colorbar, if colorbar=True.

  • cmap (str | Any | None) – Optional colormap for assigning colors to the image values, if data is not an RGB/A image. cmap must be a string or object instance which is recognized by the drawer. Defaults to None.

  • cmap_use_series_colors (bool) – Whether to assign colors to the image based on series colors, where the values inside data are series names. If cmap_use_series_colors=True,``cmap`` is ignored. This only works for two-dimensional images as three-dimensional data contains explicit colors as RGB/A values. If len(data.shape)=3, cmap_use_series_colours is ignored. Defaults to False.

  • colorbar (bool) – Whether to add a bar showing the color-value mapping for the image. Defaults to False.

  • options – Valid options for the drawer backend API.

abstract initialize_canvas()[source]

Initialize the drawer canvas.

label_for(name, label)[source]

Get the legend label for the given series, with optional overrides.

This method determines the legend label for a series, with optional overrides label and the "label" entry in the series_params option (see options). label is returned if it is not None, as this is the override with the highest priority. If it is None, then the drawer will look for a "label" entry in series_params, for the series identified by name. If this entry doesn’t exist, or is None, then name is used as the label. If all these options are None, then None is returned; signifying that a legend entry for the provided series should not be generated. Note that label_for() will convert name to str when it is returned.

Parameters:
  • name (str | int | float | None) – The name of the series.

  • label (str | int | float | None) – Optional label override.

Returns:

The legend entry label, or None.

Return type:

str | None

abstract line(x_data, y_data, name=None, label=None, legend=False, **options)[source]

Draw a line.

Parameters:
  • x_data (Sequence[float]) – X values.

  • y_data (Sequence[float]) – Y values.

  • name (str | int | float | None) – Name of this series.

  • label (str | None) – Optional legend label to override name and series_params.

  • legend (bool) – Whether the drawn area must have a legend entry. Defaults to False. The series label in the legend will be label if it is not None. If it is, then series_params is searched for a "label" entry for the series identified by name. If this is also None, then name is used as the fallback. If no name is provided, then no legend entry is generated.

  • options – Valid options for the drawer backend API.

abstract scatter(x_data, y_data, x_err=None, y_err=None, name=None, label=None, legend=False, **options)[source]

Draw scatter points, with optional error-bars.

Parameters:
  • x_data (Sequence[float]) – X values.

  • y_data (Sequence[float]) – Y values.

  • x_err (Sequence[float] | None) – Optional error for X values.

  • y_err (Sequence[float] | None) – Optional error for Y values.

  • name (str | int | float | None) – Name of this series.

  • label (str | None) – Optional legend label to override name and series_params.

  • legend (bool) – Whether the drawn area must have a legend entry. Defaults to False. The series label in the legend will be label if it is not None. If it is, then series_params is searched for a "label" entry for the series identified by name. If this is also None, then name is used as the fallback. If no name is provided, then no legend entry is generated.

  • options – Valid options for the drawer backend API.

set_figure_options(**fields)[source]

Set the figure options.

Parameters:

fields – The fields to update the figure options

Raises:

AttributeError – If an unknown figure option is encountered.

set_options(**fields)[source]

Set the drawer options.

Parameters:

fields – The fields to update the options

Raises:

AttributeError – If an unknown options is encountered.

abstract textbox(description, rel_pos=None, **options)[source]

Draw text box.

Parameters:
  • description (str) – A string to be drawn inside a report box.

  • rel_pos (Tuple[float, float] | None) – Relative position of the text-box. If None, the default textbox_rel_pos from the style is used.

  • options – Valid options for the drawer backend API.