Embeddable function plotter for Qt Quick / QtWidgets (implicit per-pixel drawing, MVVM)
pip install qmlmathplot Copy PIP instructions
An embeddable function-plotting component for Qt Quick apps. The curve is drawn per pixel by a fragment shader (implicit signed-distance model): the per-frame cost is ∝ the pixel count and independent of the function's frequency, so oscillating functions (e.g. sin(1/x)) cannot drag the frame rate down through polyline aliasing, and no CPU-side sampling is needed.
The state is a camera on an infinite canvas: a Plot holds a Camera (where you look) and a list of Curves (what is drawn), and the QML component PlotView binds to it. Several panels are several Plots in a Qt layout — there is no figure, no axes box and no page.
One line in a QtWidgets layout (least effort):
MathPlotWidget keeps one curve's worth of convenience (expression, error, line_width, curve_color, background_color, aspect, view_bounds(), reset_view(), zoom(), pan_pixels()); everything else lives on the model behind it:
plot.plot.curves.add_curve("tan(x)", color="#ff8866", label="tan") # a second curve plot.plot.camera.aspect = 1.0 # square units ("auto" by default) plot.plot.grid = False plot.plot.theme = "ggplot" Standalone window / command line:
uv run qmlmathplot "sin(1/x)" # equivalent to python examples/minimal.py … uv run qmlmathplot --backend d3d11 "sin(1/x)" # force a specific backend python examples/explorer_qtwidgets.py # function input box + sibling widgets The examples live in examples/: minimal.py is the smallest window; explorer_qtwidgets.py deliberately puts the plot widget into a "grabby" environment (input box, QScrollArea, QSplitter, overlay) to verify the widgets do not fight each other; explorer_qtquick.py (plus explorer_qtquick.qml) is the pure Qt Quick demo.
QtWidgets: MathPlotWidget is an ordinary QWidget (internally it bridges the QML component into the widgets world with a QQuickWidget and renders into its own FBO, so it can be stacked on top of / coexist with sibling widgets). Properties and methods: expression / error / line_width / curve_color / background_color / aspect, view_bounds() / reset_view() / zoom(delta, u, v) / pan_pixels(dx, dy), the signals expressionChanged / errorChanged, and the model itself as .plot.
Pure QML (Qt Quick): create the model in Python and inject it (MVVM, see below).
from PySide6.QtCore import QUrl from PySide6.QtGui import QGuiApplication from PySide6.QtQuick import QQuickView from qmlmathplot import Plot, qml_component_path, register_qml_types app = QGuiApplication([]) register_qml_types() # registers Plot, Camera, Curve and PlotView plot = Plot() # the model (owned by the app) plot.add_curve("sin(1/x)") view = QQuickView() view.setSource(QUrl.fromLocalFile(qml_component_path())) view.rootObject().setProperty("plot", plot) view.show() app.exec() import QmlMathPlot 1.0 PlotView { // inject a Plot, or let the component create its own anchors.fill: parent plot: myPlot // Arbitrary QML in world coordinates: the transform is the view's own Rectangle { x: mapToScreen(0, 0).x - 4 y: mapToScreen(0, 0).y - 4 width: 8; height: 8; radius: 4; color: "#ffcc00" } } PlotView exposes mapToScreen(x, y) / mapFromScreen(point) plus the forwarders camera and curves; input handling (pan by left-drag, wheel zoom anchored at the cursor) is built in and switchable through camera.panEnabled / camera.zoomEnabled.
Every setter is a Qt Property with a notify signal, so the same calls work from QML, from a Qt Designer slot or from a QTimer:
QTimer.singleShot(1000, lambda: setattr(curve, "expression", "sin(3/x)")) Design notes The design — the camera model, the Qt property/signal contract, the object model and the build order — is specified in docs/api-design.md. In short: the Matplotlib vocabulary is kept where it is vocabulary (limits, grid, title, ticks, annotate), while the mechanism is refused — no Figure/Axes/subplots (one view per widget, no bounded page), no FigureCanvas/draw() (the scene is live), no toolbar and no legend (host chrome), and an export is a canvas region at a pixel size rather than a re-rendered page (§9, implemented — see Export below).
Camera stores three numbers that do not depend on the widget: centre (world coordinates in the middle of the view), zoom (world units per logical pixel on x) and aspect (the ratio of the y scale to the x scale). xlim / ylim are derived from them and the last reported size, so they always say what is on screen; assigning them moves the camera.
plot = MathPlotWidget("sin(1/x)", aspect=1.0) # square units plot.aspect = "auto" # back to following the widget's shape plot.plot.camera.zoom_by(120, 0.5, 0.5, w, h) # one wheel notch, anchored at the centre Themes Plot.theme applies a style sheet to the style properties above; the default is matplotlib's own default style, so an untouched plot already looks like matplotlib and plot.theme = "default" is the reset:
plot.theme = "ggplot" # any of the bundled sheets plot.theme = "default" # back to matplotlib's look plot.theme = "my-style" # themes/my-style.mplstyle next to the package plot.theme = "path/to/any.mplstyle" # any file in the same format plot.available_themes # the names, for a host's picker (both demos use one) The 26 bundled sheets are Matplotlib's own styles, vendored verbatim into qmlmathplot/themes/*.mplstyle and converted at load time: Matplotlib's rcParams keys are mapped onto this library's property names, and keys describing things this library does not have (spines, figure size, dpi, legend, marker styles, …) are ignored. themes.names() lists them ("default" plus the 26 sheets). An unknown name raises KeyError and leaves the current theme alone.
savefig() writes a file, to_image() returns a QImage; both take the same keywords:
plot.savefig("out.png", xlim=(-1, 1), ylim=(-1, 1), width=1200, height=400) plot.savefig("hi.png", dpi=2.0) # the live view, twice the pixels image = plot.to_image(width=800, height=600) # -> QImage plot.to_image() # the live view, its own size xlim / ylim default to the camera: the live centre and scale, extended to the export size. The region is a parameter, so an export can cover more canvas than the widget shows.
width / height are device pixels and default to the live view's device size; dpi multiplies both (dpi=2.0 doubles the pixels).
adjustable reconciles a requested range with a requested size when their aspects disagree — Matplotlib's parameter, and its own default:
With no explicit range all three agree, because the range derived from the camera already has the export size's aspect.
Everything else follows the live styling (curves, grid, axes, theme), so an export cannot drift from what the user sees. Rendering goes through an offscreen QQuickWidget, so the export needs a QApplication (a clear error is raised instead of a crash if there is none).
to_matplotlib() hands the plot to matplotlib (one Axes) and savefig(..., backend="matplotlib") renders through it, so .svg/.pdf work; to_sympy() builds the same figure through sympy.plotting, which is what you want when the figure should live in sympy's world:
figure = plot.to_matplotlib(xlim=(-1, 1), ylim=(-1, 1)) # -> matplotlib.figure.Figure plot.savefig("out.svg", backend="matplotlib") # vector, matplotlib's own savefig handle = plot.to_sympy(xlim=(-1, 1)) handle.save("out.png") matplotlib is an optional extra (pip install "qmlmathplot[matplotlib]"); nothing in the package imports it until one of these is called, and the error names the extra. sympy itself is a hard dependency, so to_sympy() needs matplotlib only because its plotting backend does. Neither hand-off needs a Qt application: a Plot works in a plain script, which is what makes it usable next to a notebook or a matplotlib-only tool.
This is a second renderer, and a sampled one. matplotlib draws polylines, so each curve is evaluated at samples points (default 2000) and an oscillating function such as sin(1/x) aliases — exactly what the Qt view avoids by evaluating the expression per pixel. SymPy does not solve it either, and its adaptive mode does not help: measured on sin(1/x) over [-1, 1], sympy.plotting.plot(adaptive=True) uses 289 points (fewer than a fixed 2000), emits no warning in sympy 1.14, and draws the same block of vertical connectors. The difference is how the two fail: a sampled renderer draws an artefact, the Qt view draws the envelope the data actually supports. (to_sympy() returns the object sympy made, so its own adaptive mode is available there.) Fonts and antialiasing are matplotlib's, not the Qt view's, so the two renderers cannot look identical, and the style mapping is partial: background, grid (on/off and colour/width/alpha/dash), per-curve colour and width, tick and text colours, font sizes, title, axis colour/width, the limits, the aspect with matplotlib's own adjustable, and axes_position="zero" (spines through the origin, no box). What it buys is vector output and matplotlib's ecosystem — nothing else.
--backend {d3d11,d3d12,vulkan,metal,opengl,null}; if unspecified, Qt's default backend is used. The implementation sets QSG_RHI_BACKEND before QGuiApplication (Qt reads it during platform initialisation, and a later setGraphicsApi() has no effect). On this machine (Intel driver 32.0.101.8826) d3d11 and opengl measured pixel-for-pixel identical.
Both criteria are scale-independent and are unioned: (a) ≥ 2 direction reversals within the column (8 sample points for an ordinary pixel, topped up to 16 inside the band region); (d) the derivative prediction |f'|·dx far exceeds the measured spread (hard threshold 16× and pred ≥ 4px). One gate: a spread < 1.5 px is not filled (do not turn peak ripple into a block of colour). An ordinary pixel costs 1 f + 1 f' + 8 narrow-window samples; the wide window (±8 columns, 16 points) is only evaluated inside the band region.
uv run pytest # everything uv run pytest -m "not gui" # skip the render smoke tests that open a window QSG_RHI_BACKEND=opengl uv run pytest -m gui test_model.py: GLSL generation (small integer powers as repeated multiplication, avoiding pow(x, y)'s undefined behaviour for x 1 artefacts outside the central columns, poles not connected, nothing drawn outside the domain, and the QML furniture (grid lines exactly at the tick positions, the axes crossing at the origin with their labels on them, the axis pinning to the edge once the origin is panned away, the title). test_widget.py: MathPlotWidget coexisting with neighbouring widgets — the plot appearing inside a layout, an expression change / an invalid expression keeping the previous graph, curves added/hidden/removed through the model, the wheel over a scroll area being consumed by the plot (zoom instead of scrolling the parent), the fixed aspect being undistorted by the widget's shape, and the plot staying out of the Tab focus chain. conftest.py provides a session-scoped QApplication (QtWidgets needs one, and a process may only have one). test_qtquick_coexistence.py: the same drag conflict in Qt Quick (a Flickable must not steal the pan). test_handoff.py: the matplotlib/sympy hand-off — the figure reflects the limits, aspect, adjustable, grid, title, spines at zero and per-curve style; the sampling is uniform and NaN outside the domain (so log(x) breaks); savefig(backend="matplotlib") writes real .svg, .pdf and .png; to_sympy().save() writes a file and keeps per-curve colours; importing qmlmathplot does not import matplotlib, and hiding matplotlib produces an error naming the extra. test_export.py: to_image()/savefig() — the image is exactly the requested device size (dpi multiplies it), the no-argument form reproduces the live centre and scale, the three adjustable modes reconcile range and size as documented (a world 45-degree line stays at 45 in "box", with background margins; "stretch" fills the frame and distorts), the live camera and background survive an export, and transparent clears to alpha 0. Pitfalls near the sin(1/x) singularity (fixed — do not repeat) All of them (macro arguments, GPU sin/cos, stroke saturation on steep columns, per-column phase noise) are recorded in AGENTS.md as symptom → cause → fix with the measurements that settled them. After the fixes (1350×900, default view, D3D11 and OpenGL pixel-for-pixel identical): the singularity column of sin(1/x) is lit over a ratio of 0.50 (= half a column filling the ±1 envelope) with flat edges, and inside the central 41 columns no solid pixel falls outside |y|>1 (7961 before).
Desmos's engineering blog spells it out: sample the function into points, join them into segments, stroke along the segments; "break where neighbouring points suggest a jump"; refine extrema/zeros by bisection. The same approach is used here:
0, sqrt argument ≥ 0, asin/acos argument ∈ [−1,1]; pixels outside the domain are discarded outright. NaN/inf samples take part in neither the envelope nor segment joining.
Measured: the steep stretch of log(x) has a constant horizontal width of 1~2 device pixels (previously a tapering gradient); the thin line of sin(1/x) is uniform in width; 1/x and tan(x) are not connected across their poles; sin(x)/x^2/exp(-x²)sin(10x) are unaffected.
Startup to the first frame is about 230 ms, attributed as follows (Windows / D3D11 / 900×600):
Per-frame GPU cost (2400×1500, extreme zoom, worst case) is 31 ms; about 1/7 of that at 900×600, far below the 16.7 ms of 60 Hz. The shader source is about 6.9 KB. Every visible curve is one full-screen fragment pass, so Curve.visible is the lever when a figure carries many of them.
AGENTS.md at the repo root carries all the records (symptom → cause → fix, with the measurement that settled each one). The Qt/packaging ones that shaped the code:
Authentication is PyPI's trusted publishing (OIDC) — no API token, no repository secret. Configure it once at https://pypi.org/manage/account/publishing/ (and the same on test.pypi.org) with the owner, the repository name, the workflow file name publish.yml and the environment pypi. A project that does not exist on PyPI yet uses the "pending publisher" form there and is created by the first successful run. Running the workflow manually (Actions → Publish to PyPI → Run workflow) publishes to TestPyPI by default, so a release can be rehearsed:
pip install -i https://test.pypi.org/simple/ qmlmathplot If the publish step fails with invalid-publisher: valid token, but no corresponding publisher, the trusted-publisher entry is missing or does not match. The action prints the claims it presented (repository, workflow_ref, environment) — the entry must match them exactly, including the environment name, and it must exist on the index the run targets: a manual run goes to test.pypi.org, a tag push to pypi.org, so both need an entry.
The workflow runs on Windows: that is the platform this library is verified on (the shader baker qsb ships inside the PySide6 wheel and is only confirmed to be present there, see qsb.py), and the GUI tests need a GPU scene graph no runner has. The artifact is py3-none-any, so the platform does not change what is published. The GUI tests stay a developer-machine thing: uv run pytest (everything) versus uv run pytest -m "not gui" (what CI runs).
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Oct 10, 2026.




