# plasma_plots.charts

*module*

General charts of labeled data: parameter scans, breakdowns, cross sections, matrices.

These plots are not tied to a simulation's grid; they take 1-D arrays over a parameter or a
category, Datasets of such arrays, or plain dicts:

- [`plot_scan()`][plot_scan]: a quantity over a scanned parameter with error bars or a shaded band, e.g.
  the beam divergence over the extraction voltage, from repeated runs or their spread;
- [`plot_breakdown()`][plot_breakdown]: horizontal bars of parts of a total, e.g. the power deposited on each
  component of a beamline;
- [`plot_twin()`][plot_twin] and [`plot_stacked()`][plot_stacked]: profiles over the same coordinate with two value
  axes, or one panel per profile;
- [`plot_cross_sections()`][plot_cross_sections]: collision cross sections over energy, on log-log axes;
- [`plot_matrix()`][plot_matrix]: the non-zero pattern or the values of a (sparse) matrix;
- [`plot_child_langmuir()`][plot_child_langmuir]: a measured current density against the Child–Langmuir law;
- [`plot_variables()`][plot_variables]: every variable of a Dataset in a grid of panels.

The accessors expose them as ``array.plasma.plot.scan``, ``.breakdown``, ``.twin``, ``.stacked``,
``.cross_sections``, ``.matrix``, ``.child_langmuir`` and ``dataset.plasma.plot.variables``,
``.breakdown``, ``.cross_sections``.

**Examples**

```pycon
>>> divergence.plasma.plot.scan(x="voltage", samples="seed", band=True)
>>> power.plasma.plot.breakdown()  # power over a "component" dimension
>>> sigma.plasma.plot.cross_sections()  # cross sections over "energy"
```

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/charts.py#L1-L1)

## plasma_plots.charts.matrix_entries

*function*

```python
def matrix_entries(matrix)
```

The non-zero entries of a matrix as rows, columns and values.

**Parameters**

- `matrix` (`array_like, scipy.sparse matrix, dict or (rows, cols, values) triple`) — A dense 2-D array (or ``xarray.DataArray``), a SciPy sparse matrix (anything with ``tocoo()``), a dict with ``"row_indices"``, ``"col_indices"``, ``"values"`` and optionally ``"shape"`` (as picnic writes PETSc matrices), or a triple.

**Returns**

- (`(numpy.ndarray, numpy.ndarray, numpy.ndarray, (int, int))`) — Rows, columns, values and the matrix shape.

**Raises**

- `ValueError` — If a dense matrix is not two-dimensional.

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/charts.py#L779-L815)

## plasma_plots.charts.plot_breakdown

*function*

```python
def plot_breakdown(values, *, dim: str | None = None, ax=None, sort: bool = False, total: bool = False, annotate: bool = True, scale: float = 1.0, color=None, title: str | None = None, xlabel: str | None = None)
```

Draw the parts of a total as horizontal bars, e.g. the power deposited per component.

**Parameters**

- `values` (`(xarray.DataArray, xarray.Dataset or dict)`) — A 1-D array over a category dimension, a Dataset of scalar variables, or a dict of names to numbers (see [`prepare_breakdown()`][plasma_plots.charts.prepare_breakdown]).
- `dim` (`str`) (default: `None`) — The category dimension of an array. Default: its only dimension.
- `ax` (`matplotlib.axes.Axes`) (default: `None`) — The axes to draw into. Default: a new figure, its height from the number of parts.
- `sort` (`bool`) (default: `False`) — Order the bars by value, the largest on top. Default: ``False``, the given order from the top down.
- `total` (`bool`) (default: `False`) — Add the sum as the last bar. Default: ``False``.
- `annotate` (`bool`) (default: `True`) — Write each value, and its share of the sum, at the end of its bar. Default: ``True``.
- `scale` (`float`) (default: `1.0`) — Multiply the values, e.g. ``1e-6`` for W shown in MW (give ``xlabel`` then). Default: 1.
- `color` (`str`) (default: `None`) — The bar color. Default: the first color of the style.
- `title` (`str`) (default: `None`) — The axes title. Default: the array's label.
- `xlabel` (`str`) (default: `None`) — The value axis label. Default: the array's label and units.

**Returns**

- (`PlotResult`) — The figure, the axes, the bars, and in ``data["values"]`` the parts as drawn (see [`prepare_breakdown()`][plasma_plots.charts.prepare_breakdown]).

**Raises**

- `ValueError` — If an array is not one-dimensional, or a Dataset variable is not a scalar.

**Examples**

```pycon
>>> plot_breakdown(
...     {"duct": 0.8e6, "neutralizer": 2.1e6, "dump": 4.0e6},
...     scale=1e-6,
...     xlabel="P (MW)",
... )
>>> power.plasma.plot.breakdown(sort=True, total=True)
```

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/charts.py#L374-L470)

## plasma_plots.charts.plot_child_langmuir

*function*

```python
def plot_child_langmuir(measured, *, gap=None, voltage=None, mass=None, charge=None, initial_velocity: float = 0.0, show_error: bool = True, logx: bool = False, logy: bool = False, title: str | None = None)
```

Plot a measured current density against the Child–Langmuir law of a planar diode.

The theory is [`plasma_plots.theory.sheaths.child_langmuir()`][plasma_plots.theory.sheaths.child_langmuir], J ∝ V^{3/2} / d², in SI
units. Give the fixed one of gap and voltage; the measured array runs over the other.

**Parameters**

- `measured` (`xarray.DataArray, (x, J) pair or dict`) — The current density in A/m² over the voltage in V (with ``gap``) or over the gap in m (with ``voltage``), or a dict of labels to these, e.g. one per code.
- `gap` (`float`) (default: `None`) — The gap width d in m, for a current over voltage.
- `voltage` (`float`) (default: `None`) — The voltage V in V, for a current over the gap width.
- `mass` (`float`) (default: `None`) — The particle mass in kg. Default: the electron mass.
- `charge` (`float`) (default: `None`) — The particle charge in C. Default: e.
- `initial_velocity` (`float`) (default: `0.0`) — The injection speed in m/s (see [`child_langmuir()`][plasma_plots.theory.sheaths.child_langmuir]). Default: 0.
- `show_error` (`bool`) (default: `True`) — Add a panel with the relative difference to the law. Default: ``True``.
- `logx` (`bool`) (default: `False`) — Use a logarithmic parameter axis. Default: ``False``.
- `logy` (`bool`) (default: `False`) — Use a logarithmic current axis. Default: ``False``.
- `title` (`str`) (default: `None`) — The title. Default: ``"Space-charge-limited current"``.

**Returns**

- (`PlotResult`) — As [`plasma_plots.plotting.plot_measured_vs_theory()`][plasma_plots.plotting.plot_measured_vs_theory].

**Raises**

- `ValueError` — If not exactly one of ``gap`` and ``voltage`` is given.

> **See Also**
>
> [`plasma_plots.plotting.plot_measured_vs_theory()`][plasma_plots.plotting.plot_measured_vs_theory] : The comparison plot.

**Examples**

```pycon
>>> plot_child_langmuir(J_over_V, gap=0.01, mass=1.67e-27)  # protons
>>> J.plasma.plot.child_langmuir(voltage=5e3, logx=True, logy=True)
```

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/charts.py#L935-L1028)

## plasma_plots.charts.plot_cross_sections

*function*

```python
def plot_cross_sections(data, *, ax=None, reference=None, markers: bool = True, logx: bool = True, logy: bool = True, title: str | None = None, xlabel: str | None = None, ylabel: str | None = None)
```

Plot collision cross sections (or rate coefficients) over energy on log-log axes.

**Parameters**

- `data` (`xarray.DataArray, xarray.Dataset, dict or (energy, sigma) pair`) — The tabulated cross sections: a 1-D array over energy, a 2-D array over energy and a process dimension (one line per process), a Dataset (one line per variable), a dict of labels to any of these, or an ``(energy, sigma)`` pair.
- `ax` (`matplotlib.axes.Axes`) (default: `None`) — The axes to draw into. Default: a new figure.
- `reference` (`callable, (energy, sigma) pair or dict`) (default: `None`) — Fits or theory to compare with, drawn as black lines over the tabulated range: a function of energy, a pair, or a dict of labels to these, e.g. ``{"Janev fit": plasma_plots.theory.negative_ions.electron_detachment_cross_section}``. Default: none.
- `markers` (`bool`) (default: `True`) — Mark the tabulated points. Default: ``True``.
- `logx` (`bool`) (default: `True`) — Use a logarithmic energy axis. Default: ``True``.
- `logy` (`bool`) (default: `True`) — Use a logarithmic cross-section axis. Default: ``True``.
- `title` (`str`) (default: `None`) — The axes title. Default: ``"Cross sections"``.
- `xlabel` (`str`) (default: `None`) — The energy axis label. Default: the coordinate's label of the first array, else ``"energy"``.
- `ylabel` (`str`) (default: `None`) — The value axis label. Default: the value label of the first array, else ``"σ"``.

**Returns**

- (`PlotResult`) — The figure, the axes and the drawn lines.

**Raises**

- `ValueError` — If an array has more than two dimensions.

**Examples**

```pycon
>>> plot_cross_sections(catalogue)  # a Dataset of processes over "energy"
>>> sigma.plasma.plot.cross_sections(reference={"fit": fit})
```

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/charts.py#L663-L771)

## plasma_plots.charts.plot_matrix

*function*

```python
def plot_matrix(matrix, *, kind: str = 'pattern', ax=None, markersize: float | None = None, cmap=None, rank_boundaries=None, title: str | None = None)
```

Plot the non-zero pattern or the values of a matrix, e.g. a solver's system matrix.

**Parameters**

- `matrix` (`array_like, scipy.sparse matrix, dict or (rows, cols, values) triple`) — The matrix (see [`matrix_entries()`][plasma_plots.charts.matrix_entries]).
- `kind` (`('pattern', 'values')`) (default: `"pattern"`) — ``"pattern"`` marks each non-zero entry, colored by its sign; ``"values"`` colors the entries by value on a symmetric diverging scale. Default: ``"pattern"``.
- `ax` (`matplotlib.axes.Axes`) (default: `None`) — The axes to draw into. Default: a new figure.
- `markersize` (`float`) (default: `None`) — The marker size of a pattern. Default: from the matrix size.
- `cmap` (`str or matplotlib.colors.Colormap`) (default: `None`) — The colormap of ``kind="values"``. Default: ``"RdBu_r"``.
- `rank_boundaries` (`sequence of int`) (default: `None`) — Row (and column) indices where the part of each MPI rank begins, e.g. PETSc's ownership ranges, drawn as dashed lines. Default: none.
- `title` (`str`) (default: `None`) — The axes title. Default: the shape and the number of non-zero entries.

**Returns**

- (`PlotResult`) — The figure, the axes, the drawn artists, and in ``data`` the ``"shape"`` and the number of non-zero entries ``"nnz"``.

**Raises**

- `ValueError` — If ``kind`` is not one of the two, or a dense matrix is not two-dimensional.

**Examples**

```pycon
>>> plot_matrix(scipy.sparse.diags([1, -2, 1], [-1, 0, 1], shape=(40, 40)))
>>> plot_matrix(matrix_dict, rank_boundaries=matrix_dict["ownership_ranges"])
```

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/charts.py#L818-L927)

## plasma_plots.charts.plot_scan

*function*

```python
def plot_scan(data: xr.DataArray, *, x: str | None = None, error=None, samples: str | None = None, band: bool = False, ax=None, label: str | None = None, color=None, reference=None, logx: bool = False, logy: bool = False, title: str | None = None, xlabel: str | None = None, ylabel: str | None = None)
```

Plot a quantity over a scanned parameter, with error bars or a shaded band.

**Parameters**

- `data` (`xarray.DataArray`) — The scanned quantity over the parameter ``x``, or over ``x`` and ``samples``.
- `x` (`str`) (default: `None`) — The scanned parameter. Default: the only dimension other than ``samples``.
- `error` (`xarray.DataArray, array_like or (lower, upper) pair`) (default: `None`) — The error of each value: symmetric, or the distances below and above it. Default: the standard deviation over ``samples``, if given, else none.
- `samples` (`str`) (default: `None`) — A dimension of repeated runs (seeds, shots) to average over. Default: none.
- `band` (`bool`) (default: `False`) — Shade the error as a band around a line instead of drawing error bars. Default: ``False``.
- `ax` (`matplotlib.axes.Axes`) (default: `None`) — The axes to draw into, e.g. to compare several scans. Default: a new figure.
- `label` (`str`) (default: `None`) — The legend label; the axes then get a legend. Default: none.
- `color` (`str`) (default: `None`) — The color. Default: the next color of the style.
- `reference` (`callable, (x, y) pair or dict`) (default: `None`) — Expected curves, drawn as lines over the scanned range: a function of the parameter, an ``(x, y)`` pair, or a dict of labels to these. Default: none.
- `logx` (`bool`) (default: `False`) — Use a logarithmic parameter axis. Default: ``False``.
- `logy` (`bool`) (default: `False`) — Use a logarithmic value axis. Default: ``False``.
- `title` (`str`) (default: `None`) — The axes title. Default: the array's label.
- `xlabel` (`str`) (default: `None`) — The horizontal axis label. Default: the parameter's label.
- `ylabel` (`str`) (default: `None`) — The value axis label. Default: the array's label and units.

**Returns**

- (`PlotResult`) — The figure, the axes, the drawn artists, and in ``data["scan"]`` the values and errors (see [`prepare_scan()`][plasma_plots.charts.prepare_scan]).

**Raises**

- `ValueError` — If more than one dimension remains besides ``samples``, or the errors do not match.

**Examples**

```pycon
>>> # mean and spread of five seeds per voltage
>>> plot_scan(divergence, samples="seed", band=True, reference=theory)
>>> plot_scan(growth, error=growth_error, label="PIC", ax=ax)
```

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/charts.py#L173-L309)

## plasma_plots.charts.plot_stacked

*function*

```python
def plot_stacked(profiles, *, sharex: bool = True, height_ratios=None, step=None, logy: bool = False, title: str | None = None, figsize=None)
```

Plot profiles in panels stacked over a shared horizontal axis, one row each.

**Parameters**

- `profiles` (`sequence or xarray.Dataset`) — One entry per row: a 1-D array, or a list or dict (labels to arrays) of 1-D arrays drawn together in that row; a Dataset gives one row per variable.
- `sharex` (`bool`) (default: `True`) — Share the horizontal axis, labeled on the bottom row only. Default: ``True``.
- `height_ratios` (`sequence of float`) (default: `None`) — The relative row heights. Default: equal.
- `step` (`('pre', 'mid', 'post')`) (default: `"pre"`) — Draw step lines (see [`plasma_plots.plotting.plot_lineout()`][plasma_plots.plotting.plot_lineout]). Default: straight lines.
- `logy` (`bool or sequence of bool`) (default: `False`) — Logarithmic value axes, for every row or per row. Default: linear.
- `title` (`str`) (default: `None`) — A title above the panels. Default: none.
- `figsize` (`(float, float)`) (default: `None`) — The figure size in inches. Default: from the number of rows.

**Returns**

- (`PlotResult`) — The figure, the array of axes (one per row) and the drawn lines.

**Raises**

- `ValueError` — If there is no profile, or a profile is not one-dimensional.

**Examples**

```pycon
>>> plot_stacked([density, {"T_e": Te, "T_i": Ti}, potential])
>>> profiles_ds.plasma.plot.variables(cols=1)  # the same for a Dataset
```

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/charts.py#L562-L655)

## plasma_plots.charts.plot_twin

*function*

```python
def plot_twin(left: xr.DataArray, right: xr.DataArray, *, ax=None, step=None, logy=(False, False), colors=('C0', 'C3'), title: str | None = None, xlabel: str | None = None)
```

Plot two profiles over the same coordinate with a value axis each, left and right.

**Parameters**

- `left` (`xarray.DataArray`) — The profile on the left axis, one-dimensional.
- `right` (`xarray.DataArray`) — The profile on the right axis, one-dimensional; its coordinate may differ in values but should mean the same.
- `ax` (`matplotlib.axes.Axes`) (default: `None`) — The axes of the left profile. Default: a new figure.
- `step` (`('pre', 'mid', 'post')`) (default: `"pre"`) — Draw both as step lines (see [`plasma_plots.plotting.plot_lineout()`][plasma_plots.plotting.plot_lineout]). Default: straight lines.
- `logy` (`(bool, bool)`) (default: `(False, False)`) — Logarithmic left and right value axes. Default: both linear.
- `colors` (`(str, str)`) (default: `('C0', 'C3')`) — The colors of the two profiles, also of their axis labels and ticks. Default: the style's first color and a contrasting red.
- `title` (`str`) (default: `None`) — The axes title. Default: none.
- `xlabel` (`str`) (default: `None`) — The horizontal axis label. Default: the left profile's coordinate label.

**Returns**

- (`PlotResult`) — The figure, the two axes ``[left, right]`` and the two lines.

**Raises**

- `ValueError` — If a profile is not one-dimensional.

**Examples**

```pycon
>>> plot_twin(density, temperature)
>>> n.plasma.plot.twin(T, logy=(True, False))
```

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/charts.py#L478-L559)

## plasma_plots.charts.plot_variables

*function*

```python
def plot_variables(dataset: xr.Dataset, names=None, *, cols: int | None = None, x: str | None = None, y: str | None = None, logy: bool = False, title: str | None = None, **selection)
```

Plot every variable of a Dataset in a grid of panels, as a profile or a slice each.

After the selection a variable with one dimension left is drawn as a profile, one with two
as a slice with a color bar.

**Parameters**

- `dataset` (`xarray.Dataset`) — The variables, e.g. the output of a model at one time.
- `names` (`sequence of str`) (default: `None`) — The variables to plot, in this order. Default: every data variable.
- `cols` (`int`) (default: `None`) — The number of columns of panels. Default: up to 3.
- `x` (`str`) (default: `None`) — The dimension along the horizontal axis. Default: each variable's first remaining one.
- `y` (`str`) (default: `None`) — The dimension along the vertical axis of slices. Default: the second remaining one.
- `logy` (`bool`) (default: `False`) — Logarithmic value axes for the profiles. Default: ``False``.
- `title` (`str`) (default: `None`) — A title above the panels. Default: the Dataset's ``run`` attribute, if any.
- `**selection` (default: `{}`) — Dimensions to select, for each variable that has them: an integer is a position (``t=-1`` the last), a float the nearest coordinate value.

**Returns**

- (`PlotResult`) — The figure, the array of axes and in ``data["results"]`` the result of each panel.

**Raises**

- `ValueError` — If there is no variable, a name is not a data variable, or a variable has more than two
dimensions left after the selection.

**Examples**

```pycon
>>> state.plasma.plot.variables(t=-1)
>>> state.plasma.plot.variables(["n", "T", "phi"], cols=1, t=0.5)
```

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/charts.py#L1036-L1161)

## plasma_plots.charts.prepare_breakdown

*function*

```python
def prepare_breakdown(values, *, dim: str | None = None) -> xr.DataArray
```

The parts [`plot_breakdown()`][plasma_plots.charts.plot_breakdown] draws, as one array over a category dimension.

**Parameters**

- `values` (`(xarray.DataArray, xarray.Dataset or dict)`) — A 1-D array over a category dimension (its coordinate names the parts), a Dataset of scalar variables (one part each, named by its label), or a dict of names to numbers.
- `dim` (`str`) (default: `None`) — The category dimension of an array. Default: its only dimension.

**Returns**

- (`xarray.DataArray`) — The parts over a ``part`` dimension (or the array's own), with the names as its coordinate; units and label kept.

**Raises**

- `ValueError` — If an array is not one-dimensional, or a Dataset variable is not a scalar.

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/charts.py#L317-L371)

## plasma_plots.charts.prepare_scan

*function*

```python
def prepare_scan(data: xr.DataArray, *, x: str | None = None, error=None, samples: str | None = None) -> xr.Dataset
```

The values and errors [`plot_scan()`][plasma_plots.charts.plot_scan] draws.

**Parameters**

- `data` (`xarray.DataArray`) — The scanned quantity over the parameter ``x``, or over ``x`` and ``samples``.
- `x` (`str`) (default: `None`) — The scanned parameter. Default: the only dimension other than ``samples``.
- `error` (`xarray.DataArray, array_like or (lower, upper) pair`) (default: `None`) — The error of each value: symmetric, or the distances below and above it. Default: the standard deviation over ``samples``, if given, else none.
- `samples` (`str`) (default: `None`) — A dimension of repeated runs (seeds, shots) to average over; the values become their mean and the default error their standard deviation. Default: none.

**Returns**

- (`xarray.Dataset`) — ``value``, ``lower`` and ``upper`` (the distances of the error bar below and above the value, NaN without an error) over ``x``.

**Raises**

- `ValueError` — If more than one dimension remains besides ``samples``, ``x`` is not that one, or the
errors do not match the values.

[View source](https://github.com/max-models/plasma-plots/blob/devel/src/plasma_plots/charts.py#L106-L170)
