Skip to content

Latest commit

 

History

History
383 lines (304 loc) · 19.6 KB

plotting.md

File metadata and controls

383 lines (304 loc) · 19.6 KB

Plotting from your code (Python)

!!! info "Drawing from code is Python only" This page is about lbd.plot, LBD's Python module. From another language, save the data in an .lbd file and open it in LBD Viewer, which draws the same figure.

Make figures in Python that look exactly like LBD Viewer's, with lbd.plot (import lbd.plot as lp): the same styles (presets from the viewer's Styles page, or .lbd.json style files) and the same drawing code. There are two ways to use it:

  1. Your own matplotlib figures, in the tool's style. The viewer can't offer every figure type, so you draw anything you like with matplotlib, and lbd.plot gives it the same size, fonts, frame, ticks, colours, line widths and resolution as every other figure.
  2. The tool's plot types from Python: curves, scatter plots, heat maps, matrices, bars and 3D bars of a Dataset in memory (nothing needs to be saved first) or of an .lbd file.

Install it with the plotting extra, pip install "lbd[plot]", which adds matplotlib, pydantic and platformdirs (Language modules). Every function is listed in the API reference; to find the right one for a task, see Which function do I need?. Complete scripts with their figures are in the Examples.

Quick start

import numpy as np
import matplotlib.pyplot as plt
import lbd
import lbd.plot as lp

f = np.linspace(6.99e9, 7.01e9, 401)
p = np.arange(-60, 1, 5.0)
s21 = 1 - 0.8 / (1 + 2j * (f[None, :] - 7e9) / 0.6e6) * np.ones((len(p), 1))

# 1) Your own figure, in the style "default" (or any preset / .lbd.json file)
with lp.use("default"):
    fig, ax = plt.subplots()                      # the style's size, constrained layout
    f_ghz, f_unit = lp.prefix(f, "Hz")            # Hz -> GHz, like the tool
    for k in (0, 6, 12):
        ax.plot(f_ghz, 20 * np.log10(np.abs(s21[k])), label=f"{p[k]:g} dBm")
    ax.set_xlabel(lp.axis_label("Frequency", f_unit))
    ax.set_ylabel(lp.axis_label("|S21|", "dB"))
    ax.legend()
    fig.savefig("my_figure.pdf")                  # the style's dpi, fonts embedded

# 2) The tool's plots, straight from data in memory
d = lbd.Dataset(title="Resonator power sweep")
d.add_axis("power", p, unit="dBm", label="Power")
d.add_axis("freq", f, unit="Hz", label="Frequency")
d.add_value("S21", s21, axes=["power", "freq"])
fig = lp.plot(d, "heatmap", "S21", complex="db")
lp.save(fig, "sweep.pdf")

Choosing a style

Every function takes a style argument, in any of these forms:

Form Example Meaning
preset name "thesis" A preset from the viewer's Styles page, or the built-in default.
file path "figs/thesis.lbd.json" A style file. Any path ending in .json, or any existing file, is read as a file.
dict {"rcparams": {"font.size": 9}} Settings merged over the built-in style (partial is fine).
Style lp.load_style("thesis") A style object.
None The style saved in the file (inside the data file), else the file's preset, else the default preset, as chosen on the viewer's Styles page.

Presets are stored where the viewer keeps them (%APPDATA%\lbd\styles on Windows, ~/.config/lbd/styles on Linux), so a preset made in the viewer is available in Python at once. The environment variable LBD_CONFIG_DIR moves both. Every setting is listed in Style settings.

lp.list_styles()                          # ['default', 'paper', 'thesis']
s = lp.load_style("thesis")               # a complete Style
s.rcparams["figure.figsize"] = [170 / 25.4, 64 / 25.4]   # a wider variant (in inches) ...
s.save("thesis-wide.lbd.json")            # ... kept as a style file
lp.PresetStore().save("thesis-wide", s.diff())   # ... or as a preset the viewer shows too

Your own figures

Inside a with block

[lp.use(style)][lbd.plot.use] makes matplotlib draw with the style inside the block:

  • plt.subplots() and plt.figure() get the style's size and constrained layout;
  • lines, markers, colours, fonts, frame, ticks and grid follow the style;
  • fig.savefig() uses the style's dpi and embeds fonts.

Inside the block matplotlib draws from its own defaults with the style's rcparams over them, as LBD does, not from your matplotlibrc. When the block ends, matplotlib's previous settings come back. A style's to_rcparams() gives those rcParams, for a matplotlib.rc_context of your own.

with lp.use("thesis"):
    fig, (a1, a2) = plt.subplots(1, 2)
    a1.plot(x, y)
    a2.errorbar(x, y, yerr=dy, fmt="o")
    fig.savefig("fig3.pdf")

!!! warning "Create, draw and save inside the block" matplotlib reads some settings when a figure is drawn, not when it is created. Saving outside the block can change details such as tick marks. Use [lp.save][lbd.plot.save] if you save later: it saves inside the style.

For another size or a grid of panels, use [lp.subplots][lbd.plot.subplots]:

with lp.use("thesis"):
    fig, axs = lp.subplots(2, 1, figsize=(85 / 25.4, 120 / 25.4), sharex=True)   # in inches, as matplotlib

For a whole notebook

[lp.activate(style)][lbd.plot.activate] applies a style globally, like plt.style.use(): every later figure uses it, and every other rcParam goes back to matplotlib's own default. Undo it with plt.rcdefaults(), or activate another style.

%matplotlib inline
lp.activate("paper")          # all notebook figures in the paper style
lp.plot(d)                    # displayed inline

Figures made elsewhere

[lp.apply(fig, style)][lbd.plot.apply] restyles a Figure or Axes that was made without the style, for example by another library: background, frame, ticks, grid, and text sizes and font. Plotted data keeps its colours and line widths.

Units and labels like the viewer's

[lp.prefix][lbd.plot.prefix] puts a unit prefix on your data the way the viewer does, or uses the prefix you choose, and [lp.axis_label][lbd.plot.axis_label] writes the label in the style's unit format:

f = np.linspace(4e9, 8e9, 401)
f_ghz, unit = lp.prefix(f, "Hz")              # automatic: values in GHz, unit "GHz"
f_mhz, unit_m = lp.prefix(f, "Hz", to="M")    # your choice, for any unit: MHz
lp.axis_label("Frequency", unit)              # "Frequency (GHz)"

Automatic prefixes work for base units (Hz, s, V, A, m, g, …); for any other unit, pass the prefix you want (to="m") or to="", otherwise you get a warning that nothing was changed. LBD only adds prefixes, it never converts between units. See Unit prefixes.

The tool's plot types

From a dataset or file

[lp.plot][lbd.plot.plot] draws a curve, scatter, heat map, matrix, bars or 3D bars exactly like LBD Viewer. data is a Dataset in memory or an .lbd path; the other arguments are the plot settings: LBD's data choices, matplotlib's own groups as dicts (axes, right_axes, mappable, kwargs, lines, calls) and each plot type's own choices in lbd. Settings saved in the file's view are used unless you override them, as in the viewer; a group you give goes over the saved one property by property. The result is a normal matplotlib figure, drawn in the file's numbers (ax.get_xlim() of a frequency stored in Hz is in Hz; the tick labels show GHz): add lines, change limits, then plt.show() or lp.save(...). Saving one figure again, in the same format or another, gives the same picture as the first save.

fig = lp.plot("sweep.lbd")                                   # the file's saved view and style
fig = lp.plot(d, "curve", "S21", complex="phase_deg", series="power")
fig = lp.plot(d, "curve", "S21", series="power", style={"rcparams": {"lines.marker": "."}})   # a dot on every point
fig = lp.plot(d, "curve", "S21", complex="db", series="none", axes={"xscale": "log", "xlim": [5e9, 8e9]})
fig = lp.plot(d, "scatter", "S21", complex="iq", color="power", style="thesis")

For few positions, a matrix shows the numbers themselves and bars compare them. A type's own choices go in lbd, under the type's name; the 3D bars' angle is matplotlib's view_init:

m = lbd.Dataset(title="Assignment")
m.add_axis("prepared", [0.0, 1.0], label="Prepared", elements=["ground", "excited"])
m.add_axis("measured", [0.0, 1.0], label="Measured", elements=["ground", "excited"])
m.add_value("p", [[0.97, 0.03], [0.06, 0.94]], axes=["prepared", "measured"], label="Probability")
fig = lp.plot(m, "matrix", "p", lbd={"matrix": {"digits": 2}})
fig = lp.plot(m, "bars", "p", x="prepared", series="measured", lbd={"bars": {"layout": "stacked", "numbers": True}})
fig = lp.plot(m, "bars3d", "p", kwargs={"view_init": {"elev": 25, "azim": -60}})

A new scatter plot (no color, all or index given, and no scatter view saved in the file) starts as LBD Viewer does: an axis with names for its points, at most 32 of them, gives the colours; the longest other axis keeps all its points; the others are fixed (sliders in the viewer). color="none" and all=[...] choose yourself; a saved scatter view without all takes all the points, unless index fixes an axis. With all, the axes listed keep all their points and the others not drawn are fixed; axes={"aspect": "equal", "adjustable": "datalim"} gives the same scale both ways:

fig = lp.plot(d, "scatter", "S21", complex="iq", color="none", all=["freq"], index={"power": 0})

Figures draw the stored numbers. What computes new numbers from them is in LBD Viewer's Explore only: histograms, a statistic per bar over All (stat) with its error bars (errors), a matrix's row sums (row_sums), and the histograms beside a scatter plot (sides). lp.plot refuses them with what to do, and a saved view that uses one is drawn without it (with a warning; the file keeps it, for Explore). Compute what you need and draw it, in LBD's style:

import numpy as np

shots = np.random.default_rng(0).normal(0.2, 0.05, 5000)        # e.g. a value read with lbd.load
counts, edges = np.histogram(shots, bins=40)
fig, ax = lp.subplots()                                  # a figure in LBD's style
ax.stairs(counts, edges, fill=True)
ax.set_xlabel("Signal")
ax.set_ylabel("Count")

A whole example, mean ± standard deviation with error bars and a histogram from a file: Statistics and other computed plots.

To count numbers of your own, count_bins does what the plot does:

from lbd.plot.histogram import auto_bins, count_bins

numbers = np.abs(d["S21"].data).ravel()
edges, counts = count_bins(numbers, auto_bins(numbers))

Lines, text, arrows and shapes are matplotlib calls (calls), passed the same way or stored in the file's saved view with lbd.set_plot, so the viewer draws them too. Their numbers are the file's numbers, as stored: 6 GHz stored in Hz is 6e9, whatever prefix the axis shows (details):

fig = lp.plot("sweep.lbd", "curve", "S21", complex="db", series="none",
              calls=[
                  {"method": "axvline", "args": [6e9], "kwargs": {"linestyle": ":"}},
                  {"method": "annotate", "args": ["probe tone"],
                   "kwargs": {"xy": [6e9, 0], "xytext": [0.05, 0.85], "textcoords": "axes fraction",
                              "arrowprops": {"arrowstyle": "->"}}},
                  {"patch": "Rectangle", "args": [[5.5e9, -0.5], 1e9, 1.0], "kwargs": {"fill": False}},
              ])

A variable sweep of two levels (an axis group: say Frequency chosen per Power) is drawn as the viewer draws it: lp.plot(d, "curve", "S21") gives one curve per power against its own real frequencies (x="freq", the default), x="power" one curve per position inside a step, and x="freq_n" (the position inside a step) the points numbered. A value with one number per power can join with x="power". lp.table gives the same lines, each stored point once.

Pass ax= to draw into one panel of a larger figure:

with lp.use("thesis"):
    fig, (a, b) = lp.subplots(1, 2, figsize=(170 / 25.4, 64 / 25.4))
    lp.plot(d, "heatmap", "S21", complex="db", ax=a, style="thesis")
    lp.plot(d, "curve", "S21", complex="db", series="none", index={"power": 0}, ax=b, style="thesis")
    a.set_title("(a)", loc="left")
    b.set_title("(b)", loc="left")
lp.save(fig, "fig2.pdf", style="thesis")

From plain arrays

[lp.quick][lbd.plot.quick] plots arrays with the tool's look, without building a Dataset:

Use Call
One curve lp.quick(t, v, x_label="Time", x_unit="s", y_label="Signal", y_unit="V")
Several curves lp.quick(t, {"data": v, "fit": v_fit}); the keys become the legend
Scatter against x lp.quick(f, t1, kind="scatter", x_label="Frequency", x_unit="Hz", y_label="T1", y_unit="s")
Value against value lp.quick(i, q, kind="scatter"); when x isn't sorted, the points are plotted pairwise
Coloured scatter add color=power, color_label="Power", color_unit="dBm"
Heat map `lp.quick(f, p, z=Z, z_label="
t = np.linspace(0, 1e-6, 201)
fig = lp.quick(t, {"data": np.sin(2e7 * t), "fit": 0.9 * np.sin(2e7 * t)},
               x_label="Time", x_unit="s", y_label="Signal", y_unit="V")

As numbers: a CSV table

[lp.table][lbd.plot.table] gives the numbers a curve plot or heat map shows (the complex mode applied, the series and slices chosen), with the same arguments as lp.plot. This is what LBD Viewer's Save as CSV writes (Explore). A value whose data points are vectors or matrices is drawn only as what means something for it: a vector as "curve", "bars" or "scatter" (one element against another, named bloch.x, bloch.y …: lp.plot(d, "scatter", "bloch.z", x="bloch.x"), coloured by the sweep), a matrix as "matrix", "bars3d" or "curve" (one curve per entry). Another type is refused with the reason and the types that are offered.

to_csv writes one data point per row, or for 2-D data a table (matrix):

t = lp.table("sweep.lbd", "curve", "S21", complex="db", series="power")
t.to_csv("sweep_S21_dB.csv")                       # columns power, freq, S21
t.to_csv("sweep_matrix.csv", layout="matrix")      # rows = power, columns = freq

a = np.loadtxt("sweep_S21_dB.csv", delimiter=",", encoding="utf-8")
cols = np.genfromtxt("sweep_S21_dB.csv", delimiter=",", names=True, encoding="utf-8")
print(cols["freq"][:3], cols["S21"][:3])
Argument Choices
numbers= "shown" (as plotted), "stored" (the file's numbers; complex as S21_re, S21_im), "both"
xlim=, ylim= keep only this range (stored units: Hz, not GHz)
to_csv(layout=) "rows" or "matrix"; rows_are="x" turns the matrix the other way

Numbers are in the units stored in the file, as LBD Viewer's Save as CSV writes them. (units= was removed in LBD 2.0.)

The file starts with comment lines (#): the column names, where the numbers come from (file, the file's id and the parent_id it was made from, complex mode, fixed parameters, what the numbers of an axis with elements stand for, such as state (Prepared state): 0 = ground, 1 = excited), and each column's unit. Numbers are written at full precision, with . as decimal point and , between columns. Give encoding="utf-8" when reading: units like µ and ° are in the comments. t.estimate() says how big the file will be before writing it.

The whole file as CSV

A file can hold values on different axes, for example u(A), v(A, B) and t(C). A table holds one group, the values on the same axes (mixed, most of its cells would be empty). [lp.groups][lbd.plot.groups] lists them; lp.table(..., group=) makes a group's table, as stored, for any number of axes: a column per axis, then per value, a row per data point. A complex value is two columns (S21_re, S21_im), a data point of several numbers a column each, and a variable sweep gives each point its coordinates. Single numbers and the metadata are in the comments. A file is read block by block, so it may be bigger than memory.

for g in lp.groups("sweep.lbd"):
    print(g.label, g.rows)                         # S21, ... (power, freq) 1234
lp.table("sweep.lbd", group="S21").to_csv("sweep_all.csv")

Recipes

Make every figure of a paper consistent

See Consistent figures in your own code.

Plot data before saving it

d = lbd.Dataset(title="live")
d.add_axis("freq", f, unit="Hz", label="Frequency")
d.add_value("S21", np.exp(1j * f * 1e-9), axes="freq")    # your measurement here
fig = lp.plot(d, complex="db")                # look at it
d.save("run_042.lbd")                         # keep it if it's good

A style for matplotlib users without LBD

open("paper.mplstyle", "w").write(lp.load_style("paper").to_mplstyle())
# colleagues: plt.style.use("paper.mplstyle")

Errors and warnings

Nothing is ignored silently. A call that can't do what you asked raises an error; a call that worked but ignored or adjusted something gives a warning.

When
[StyleError][lbd.plot.StyleError] (a ValueError) Unknown preset, unreadable style file, an unknown setting (the message suggests the closest name: rcparams.font.sise → did you mean 'font.size'?), a setting a style can't set (the message says why), an invalid value (the message names it), or drawing with a font that isn't installed (the message lists the fonts you can use). A style made by an older LBD raises OlderStyleError, a kind of StyleError: it is not read.
[RenderError][lbd.plot.RenderError] (a ValueError) The plot can't be made: an unknown value or axis, a heat map of a 1-D value, an index out of range, a property or method matplotlib doesn't have, a call that does what a setting does (one home for each setting)… The message lists the valid choices.
TypeError / ValueError An argument of the wrong type or shape, e.g. color= for a curve, arrays of different lengths in quick.
ImportError lbd.plot imported without pip install "lbd[plot]".
[RenderWarning][lbd.plot.RenderWarning] A setting doesn't apply to the plot type (color on a curve), or the file's saved view refers to a value that no longer exists. The title is wider than the figure, so both its ends are cut off: shorten it or make the figure wider.
[StyleWarning][lbd.plot.StyleWarning] A style file (or the style saved in an .lbd file) has settings this version doesn't know; they are ignored. The file's style preset doesn't exist on this computer. The file's saved view or style was made by an older LBD and is not read (lbd.load says so once).
[UnitWarning][lbd.plot.UnitWarning] An automatic unit prefix was asked for a unit that doesn't get one (e.g. dBm).

Notes

  • lp.plot and the viewer use the same functions, so the same data, plot settings and style give pixel-identical results. A test checks this.
  • lp.plot creates figures with pyplot, so they appear in Jupyter and with plt.show(). The viewer itself never uses pyplot.
  • Figures from lp.plot keep their tick and text settings even when saved with a plain fig.savefig() outside the style, and the same automatic ticks as on screen in every format. Only the automatic layout may then differ by a fraction of a pixel. lp.save gives byte-identical files.