Skip to content

Plotting utils

plotting_utils

Attributes

COLORS module-attribute

COLORS = (
    "blue",
    "red",
    "green",
    "black",
    "orange",
    "purple",
    "brown",
    "cyan",
)

The colours used when a trace does not prescribe one.

DASHES module-attribute

DASHES = ('solid', 'dash', 'dot', 'dashdot')

The dash patterns used to distinguish the traces of superposed sources.

DASH_ALIASES module-attribute

DASH_ALIASES = {
    "-": "solid",
    "--": "dash",
    "-.": "dashdot",
    ":": "dot",
    "..": "dot",
}

The Matplotlib dash patterns mapped to their Plotly counterparts.

MARKER_ALIASES module-attribute

MARKER_ALIASES = {
    ".": "circle",
    "o": "circle",
    "x": "x",
    "+": "cross",
    "s": "square",
    "^": "triangle-up",
    "v": "triangle-down",
    "*": "star",
    "d": "diamond",
}

The Matplotlib marker symbols mapped to their Plotly counterparts.

Classes

Functions:

get_formatted_value

get_formatted_value(
    value, precision: int = FLOAT_PRECISION
)

Rounds either a float or a NumPy array.

Parameters:

  • value –

    The data to round.

  • precision (int, default: FLOAT_PRECISION ) –

    The rounding precision.

Returns: The rounded data.

Source code in src\vimseo\utilities\plotting_utils.py
320
321
322
323
324
325
326
327
328
329
330
331
332
def get_formatted_value(value, precision: int = FLOAT_PRECISION):
    """Rounds either a float or a NumPy array.

    Args:
        value: The data to round.
        precision: The rounding precision.

    Returns: The rounded data.
    """
    is_float = isinstance(value, float)
    if is_float:
        return str(round(value, precision))
    return array_str(atleast_1d(value), precision=precision)

superpose_curves

superpose_curves(
    sources: CurveSet | Curve | Iterable[CurveSet | Curve],
    variable_names: Iterable[str] = (),
    labels: Iterable[str] = (),
    directory_path: str | Path = "",
    save: bool = False,
    show: bool = True,
    file_name: str | Path = "",
    fig: Figure | None = None,
) -> Figure

Superpose curves on a single figure.

The curves are given either individually, or bundled into the :class:.CurveSet of a figure, which also carries their style. This handles the two kinds of superposition:

  • the traces of a single :class:.CurveSet, i.e. several ordinate variables of a single model result, styled by its plot specification,
  • the same curve coming from several results, e.g. to compare the runs of a database, in which case labels identifies each result.

Parameters:

  • sources (CurveSet | Curve | Iterable[CurveSet | Curve]) –

    The curve sets or curves to draw. They shall all share the same abscissa variable.

  • variable_names (Iterable[str], default: () ) –

    The names of the ordinate variables to draw. All of them by default.

  • labels (Iterable[str], default: () ) –

    The label of each source, used as a legend prefix.

  • directory_path (str | Path, default: '' ) –

    The path where to save the figure.

  • save (bool, default: False ) –

    Whether to save the figure.

  • show (bool, default: True ) –

    Whether to show the figure.

  • file_name (str | Path, default: '' ) –

    The name of the file to save the figure to.

  • fig (Figure | None, default: None ) –

    A figure to draw on. A new one is created when None.

Returns:

  • Figure –

    The figure.

Raises:

  • ValueError –

    When the sources do not share the same abscissa variable.

Source code in src\vimseo\utilities\plotting_utils.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
def superpose_curves(
    sources: CurveSet | Curve | Iterable[CurveSet | Curve],
    variable_names: Iterable[str] = (),
    labels: Iterable[str] = (),
    directory_path: str | Path = "",
    save: bool = False,
    show: bool = True,
    file_name: str | Path = "",
    fig: Figure | None = None,
) -> Figure:
    """Superpose curves on a single figure.

    The curves are given either individually, or bundled into the
    :class:`.CurveSet` of a figure, which also carries their style.
    This handles the two kinds of superposition:

    - the traces of a single :class:`.CurveSet`, i.e. several ordinate variables of
      a single model result, styled by its plot specification,
    - the same curve coming from several results, e.g. to compare the runs of a
      database, in which case ``labels`` identifies each result.

    Args:
        sources: The curve sets or curves to draw.
            They shall all share the same abscissa variable.
        variable_names: The names of the ordinate variables to draw.
            All of them by default.
        labels: The label of each source, used as a legend prefix.
        directory_path: The path where to save the figure.
        save: Whether to save the figure.
        show: Whether to show the figure.
        file_name: The name of the file to save the figure to.
        fig: A figure to draw on. A new one is created when ``None``.

    Returns:
        The figure.

    Raises:
        ValueError: When the sources do not share the same abscissa variable.
    """
    curve_sets = _as_curve_sets(sources)
    labels = list(labels)

    variable_names = list(variable_names)
    if variable_names:
        curve_sets = [
            _select_variables(curve_set, variable_names) for curve_set in curve_sets
        ]

    _check_abscissa_names(curve_sets)

    n_sources = len(curve_sets)
    spec = curve_sets[0].spec if curve_sets else None
    has_secondary = any(
        trace.secondary_y for curve_set in curve_sets for trace in curve_set.spec.traces
    )

    if fig is None:
        fig = (
            make_subplots(specs=[[{"secondary_y": True}]])
            if has_secondary
            else Figure()
        )

    colors_by_axis = {False: [], True: []}
    names_by_axis = {False: [], True: []}

    for source_index, curve_set in enumerate(curve_sets):
        source_label = labels[source_index] if source_index < len(labels) else ""
        curve_index = 0
        for trace_index, trace in enumerate(curve_set.spec.traces):
            color = _resolve_color(trace.style, source_index, trace_index, n_sources)
            dash = _resolve_dash(trace.style, trace_index, n_sources)
            label = _resolve_label(trace, source_label, n_sources)

            if isinstance(trace, ConstantTrace):
                x_min, x_max = curve_set.x_range
                x_values = [x_min, x_max]
                y_values = [trace.value, trace.value]
                ordinate_name = trace.get_label()
            else:
                curve = curve_set.curves[curve_index]
                curve_index += 1
                x_values = curve.x
                y_values = curve.y
                ordinate_name = trace.y

            scatter = _make_scatter(x_values, y_values, label, trace.style, color, dash)
            if has_secondary:
                fig.add_trace(scatter, secondary_y=trace.secondary_y)
            else:
                fig.add_trace(scatter)

            colors_by_axis[trace.secondary_y].append(color)
            if ordinate_name not in names_by_axis[trace.secondary_y]:
                names_by_axis[trace.secondary_y].append(ordinate_name)

    if spec is not None:
        fig.update_xaxes(title_text=spec.x_label or spec.x)
        _set_ordinate_axis(
            fig,
            spec.y_label or ", ".join(names_by_axis[False]),
            colors_by_axis[False],
            secondary_y=False,
            has_secondary=has_secondary,
        )
        if has_secondary:
            _set_ordinate_axis(
                fig,
                spec.y_label_secondary or ", ".join(names_by_axis[True]),
                colors_by_axis[True],
                secondary_y=True,
                has_secondary=has_secondary,
            )
        if spec.title:
            fig.update_layout(title_text=spec.title)

    file_name = "curves.html" if file_name == "" else file_name
    if save:
        directory_path = Path(directory_path)
        if str(directory_path) != "." and not directory_path.exists():
            directory_path.mkdir(parents=True)
        fig.write_html(str(directory_path / file_name))
    if show:
        fig.show()

    return fig