fplotlib#
Pure Fortran plotting library with a pylab-style API, writing SVG, PNG, PDF and EPS. No external graphics library: the PNG rasterizer and its fonts are part of fplotlib.
use fplotlib
call plot(x, y, "k-", label="sin")
call title("My plot")
call xlabel("x")
call ylabel("y")
call grid(.true.)
call legend()
call savefig("out.svg") ! or "out.png", "out.pdf", "out.eps"
call show() ! Jupyter (LFortran) or writes fplotlib_show.svg
! subplots
call clf()
call subplot(2, 1, 1)
call plot(x, y, "b-", label="sin")
call title("top")
call subplot(2, 1, 2)
call plot(x, y2, "r--", label="cos")
call title("bottom")
call suptitle("figure title")
Features#
plot,scatter,bar,hist,fill_between,errorbarbartakesyerr=,capsize=,align="edge"andtick_label=;errorbartakesecolor=,elinewidth=,lw=andalpha=plot(y)with a single array numbers the points0, 1, 2, ...for xxlim/ylimto set,get_xlim/get_ylimto read back what autoscaling chose, andinvert_xaxis/invert_yaxisto make an axis count downscatteralso takes per-pointsizes=and color-mappedcvals=(separate keywords because Fortran cannot overload one dummy as scalar-or-array the way matplotlib’ss=andc=do)step,stem,barh,pie,boxplot,violinplotboxplot(y)for one dataset orboxplot(y(:,:), labels=)for a row each, withvert=,notch=,showmeans=,patch_artist=andwhis=violinplotthe same way, withvert=,showmeans=,showmedians=andshowextrema=pie(explode=, startangle=, counterclock=, autopct=, pctdistance=, labeldistance=, radius=, colors=, edgecolor=, linewidth=)semilogx,semilogy,loglog,axhline,axvlinefill_betweenxfor a band along y,stackplotfor layers summed on top of each other, andaxlinefor an endless line through two points or through one with aslope=textandannotate(arrowstyle="->"draws a leader with a head at the annotated point, witharrowcolor=,arrowlw=andshrink=), withrotation=,va=, abbox_facecolor=box behind them and lines broken atachar(10);figtextplaces on the canvas instead of in the axes, andtransform="axes"places in fractions of the axes box.connectionstyle="arc3,rad=0.3"bows the leader out of the straight line, andboxstyle="round,pad=0.5"rounds the corners of the boxtextboxplaces a rich MyST Markdown block (bold, italic, inline and displayed TeX math, lists, Knuth–Plass justification and hyphenation) in axes, figure, or data coordinates, with optional roundedfacecolor=,edgecolor=,pad=andradius=for inset cards, wrapped titles, and figure captionsimshowof an (row, column, channel) array paints the colours given, three channels for RGB or four for RGBAimshowwithcmap,extent,origin,vmin/vmaxand square-pixelaspect, pluscolorbar(label=, orientation=, fraction=, pad=, shrink=, aspect=), upright or lying on its sidecontourandcontourfwith automatic or explicitlevelsColormaps:
viridis,plasma,inferno,magma,gray,coolwarmFormat strings: colors
bgrcmykw/C0–C9, linestyles---:-., markerso x . s ^ v < > * + DOptional
label=,lw=,color=,marker=,alpha=hatch=on bars, fills and patches:/,\,|,-,+andx, repeated to pack the lines closer, ruled across the shape and clipped to it (matplotlib’s dotted hatches are not drawn)Marker and line detail on
plot:markersize=,markerfacecolor=,markeredgecolor=,markeredgewidth=,markevery=,drawstyle=and adashes=pattern of your ownTitle, axis labels, grid,
xlim/ylim,clf/figure(figsize=, dpi=)set_facecolor(color, alpha=)for the background of one axesgrid(on, axis=, which=, color=, linestyle=, lw=, alpha=)for one axis only, for the minor ticks, or in a colour of your own; log axes carry minor ticks without being asked, as matplotlib’s dosavefig(file, transparent=, facecolor=); the extension picks the format, one of.svg,.png,.pdfor.eps, anddpi=sizes the PNG rasteraxis("on"|"off"|"equal"|"scaled"|"tight"|"auto")andset_aspectmargins(m)ormargins(x=, y=)for the room left past the data, andautoscale(enable, axis=, tight=);autoscale(.false.)pins the limits where the data has put them so far, so nothing drawn later moves themset_xscale/set_yscalewith"linear","log"or"symlog"tick_params(axis=, direction=, length=, labelsize=, rotation=)andspineslegend(loc=, fontsize=, ncol=, frameon=, title=, bbox_to_anchor=, labels=), placed where the data leaves most room whenlocis left out, as matplotlib’s"best"does; a label starting with_keeps its artist out of the legend,figlegend(loc=, fontsize=, ncol=, frameon=, title=)for one legend covering every panel,xticks/ytickswith optional labels,minorticks_on,xticks(vals, minor=.true.)to place minor ticks by hand, andlocator_params(axis=, nbins=, prune=)Formatters and locators:
tick_format(axis, "percent"/"comma"/"fixed"),tick_locator(axis, base=, nbins=)andticklabel_format(style=, useoffset=, scilimits=). An axis whose labels would otherwise repeat themselves factors the shared offset and power of ten out into a single label at its end, as matplotlib’s ScalarFormatter doesFont sizes:
fontsize=ontitle/xlabel/ylabel/suptitle, andset_fontsize(size=, title=, labels=, ticks=, legend=)to set them globallytitle(loc="left"|"right")andxlabel/ylabel(labelpad=)savefig(dpi=, bbox_inches="tight", pad_inches=)to crop to the drawingSeveral live figures at once:
figure(num=),gcf(),close(num=, all=)subplots(m, n, axs, sharex=, sharey=)hands back axes handles, socall axs(1,2)%plot(x, y)works alongside the statefulsubplotstyle; shared axes span the union of the group and drop their inner tick labels. Every call the stateful interface offers is also a method on the handleSubplots:
subplot(m, n, i)and figure-levelsuptitle; per-axes state (series, labels, grid, legend, scale, limits) with matplotlib’s default subplot spacingsubplots_adjustandtight_layoutconstrained_layout(.true.): the same fit, but made afresh at draw time, so labels added after the plotting still get their room. Ours keeps one margin for the whole grid where matplotlib works row by rowtwinxandtwinyfor a second y or x axis on the same plotBars:
bar/barhwithbottom=/left=for stacks,colors=for a color per bar,edgecolor=/linewidth=, andbar_label(fmt=, padding=)add_axesfor an axes placed by hand,inset_axesfor a small axes inside another, andsecondary_xaxis/secondary_yaxisfor a second scale along an edgetablefor a block of text below (or above) the axesstreamplotfor the streamlines of a vector fieldadd_frame/save_animation(file, fps=, loop=)to write an animated GIF, or a full-colour animated PNG with a.pngor.apngfile namespy(sparsity pattern of a dense matrix or COO indices),matshow,eventplotandbroken_barhhist2dandhexbinfor counting points into square or hexagonal binsimshow(interpolation="bilinear")to smooth an image instead of showing it as blocks3D axes:
plot3d,scatter3d,plot_surface(flat orcmap=) andplot_wireframe, withview_init,zlabelandzlim, drawn with mplot3d’s camera, panes and lightingPolar axes:
polar(theta, r), orset_polar()on an axes, with the angular grid, the degree labels and the radial labels along 22.5°Layered like matplotlib: images below patches, the grid above the patches and below the lines, text on top, with
set_zorderto lift the artist just drawn out of that orderMissing data: a NaN or an infinity breaks the line and the band there and takes no part in the limits, as it does in matplotlib
Patches:
add_rectangle,add_circle,add_ellipse,add_polygon,add_arrowandadd_pathfor an arbitrary path of lines and cubics, filled and outlined in data coordinatesclabelto write the level into each contour line, breaking the line at its straightest stretch to make roomquiverfor a field of arrows, sized as matplotlib sizes them, andquiverkeyfor a reference arrow drawn to the same scaleDate axes:
date_num(y, m, d)for the numbers andxaxis_date()to have the ticks land on round dates and read as datessubplot2grid: panels that span several cells of a grid, so a wide plot can sit over two narrow onessubplot_mosaic(["AB", "CC"], keys, axs): the panels drawn as a small picture of the figure, one character per cell, a panel per charactergridspec(width_ratios=, height_ratios=): columns and rows of unequal size, for a wide panel beside a narrow onepcolormeshandpcolor: a grid of cells with edges of your own choosing, which is what an unevenly sampled field needstriplotandtripcolor: scattered points joined into triangles by the same Delaunay triangulation matplotlib gets from Qhull, drawn as edges or filled by valuetricontourandtricontourf: level lines and filled bands over those same triangles, with matplotlib’s rounded levels and a colorbarplot_trisurf: those triangles lifted into three dimensions and lit by the same light sourceplot_surfaceusesbar3d: boxes standing on the xy plane, six lit faces each, painted back to front with everything else in the axesquiver3d: arrows in space, a shaft and two barbs turned fifteen degrees off it, with the limits taken from where the arrows startcontour3d: level lines of a grid drawn in space, each at the height of its own levelmatplotlib’s tick locator and formatter: the same 1/2/2.5/5 steps, the same number of ticks for the space available, and one decimal count shared by the whole axis. A log axis writes its decades as powers, and when it spans a decade or less it labels the multiples between them
Mathtext: TeX math in any label (
$E = mc^2$,$x_i^2$,$\frac{a}{b}$,$\sqrt[3]{x}$), set in Lete Sans Math with TeX’s layout (The TeXbook, Appendix G) driven by the font’s OpenType MATH table, as XeTeX, LuaTeX and Typst do: script sizes and alternates, script shifts, math kerns and italic corrections, fractions, radicals, size variants and assemblies all come from the font. Supported are the greek letters, about two hundred operators, relations, arrows and other symbols; primes;\frac,\dfrac,\tfrac,\cfrac,\binom,\over,\atopand\choose; large operators with limits (\sum,\int,\lim,\limits,\nolimits) and the named functions (\sin,\log,\operatorname{erf}) in Lato;\left,\middleand\right, and\bigto\Bigg; accents (\hat,\bar,\vec,\widehat, …),\overlineand\underline; the alphabets\mathrm,\mathit,\mathbf,\mathsf,\mathbband\mathcal;\textin Lato; the four styles (\displaystyle, …) and TeX’s spaces (\,,\quad, …); and the alignmentsmatrix,pmatrix,bmatrix,Bmatrix,vmatrix,Vmatrix,cases,array,alignedandgathered.tests/math_refs.txtholds where XeTeX puts every glyph and rule of 92 test formulas, and the layout is checked against itAutomatic delimiters, as Typst has them: matched
( ),[ ],\{ \},| |,\| \|,\langle \rangle,\lfloor \rfloorand\lceil \rceilgrow to fit what they enclose, so$(\frac{a}{b})$needs no\leftand\right, and a|between them grows with them. They never shrink, so$f(x)$keeps its plain parentheses; unmatched ones ($[0, 1)$), escaped ones (\(,\[) and ones in braces ({(}) stay plain.tests/delim_refs.txtholds the sizes Typst chooses for 29 formulasText is UTF-8 and set in Lato (regular, bold and italic; bold italic is set in bold), with its kerning, in every European script except Cyrillic. The outlines are compiled in, so every format draws the same glyphs: PNG fills them, SVG defines each once and
<use>s it, and PDF and EPS embed them as Type 3 fonts that keep the text selectable. Tick labels write their minus as U+2212, as matplotlib doesfontweight=andfontstyle=ontitle,suptitle,xlabel,ylabel,textandannotate: real bold and italic faces, not a smeared or sheared regular oneCategorical axes:
plot,barandbarhtake a list of names in place of the numbers, and place them at 0, 1, 2, … with the names as ticks49 matplotlib colormaps, plus the qualitative
tab10,tab20andSet1, any of them reversed with a_rsuffiximshow(norm="log")for a logarithmic color scale, andimshow(boundaries=)for matplotlib’sBoundaryNorm: one flat color per band, and a colorbar of blocks to matchnorm="centered"withvcenter=,norm="power"withgamma=andnorm="symlog"withlinthresh=, onimshowandpcolormeshset_bad,set_underandset_overfor the samples a colormap has nothing to say about, andset_cmap_colorsto build one from a list of stops; missing samples are left clear unlessset_badsays otherwiseerrorbarwithxerr=and asymmetricyerr_lo=/yerr_hi=armsfill_between(where=, interpolate=)to shade only where a condition holds, carried out to the crossing pointscatter(edgecolors=, linewidths=)to outline the markershist(bins=, bin_edges=, density=, cumulative=, histtype="step"/"stepfilled", weights=, stacked=, orientation="horizontal", log=, rwidth=)axhspan/axvspanshaded bands andhlines/vlinesline runsstyle_use("ggplot")and friends (seaborn,fivethirtyeight,dark_background,grayscale,default), orrc(figsize=, dpi=, fontsize=, linewidth=, grid=, facecolor=, axes_facecolor=, grid_color=, text_color=, color_cycle=)for one setting at a timeColors as CSS4/X11 names,
tab:names,#rgb,#rrggbb,#rrggbbaa, single letters,C0-C9, or a greyscale fraction such as"0.5"SVG defaults aligned with matplotlib (6.4×4.8 in, tab10 colors, subplot margins)
Documents#
typeset sets a whole document, written in Markdown with TeX mathematics
($...$ inline, $$...$$ displayed), and writes it as PDF, or as one SVG,
PNG or EPS file per page:
call typeset([character(len=80) :: &
"---", &
"title: Notes", &
"numbersections: true", &
"---", &
"# Energy", &
"", &
"The energy of a mass at rest is", &
"$$ E = mc^2 $$ (eq:einstein)", &
"and {eq}`eq:einstein` is the best known formula of physics."], "notes.pdf")
typeset_file reads Markdown from one file or an array of files (front matter
from the first, labels and cross-references resolved across all of them):
call typeset_file("chapter1.md", "chapter1.pdf")
call typeset_file([character(len=32) :: "ch1.md", "ch2.md"], "book.pdf")
The bundled CLI runs typeset_file from the command line:
fpm run typeset -- ch1.md ch2.md -o book.pdf
The built-in :::{literalinclude} path directive includes a source file as a
code block, resolving relative paths against the Markdown file’s directory,
with optional :lines: (e.g. 1-10, 5-, -10, 1-3, 7-9) and :language:
options.
Markdown pipe tables (| A | B | with :---, :---:, ---: column
alignments) and the :::{table} Caption directive are rendered in booktabs
style and numbered for {numref} / {ref} cross-references.
For building reports directly inside a Fortran simulation without managing
intermediate files, use the immediate-mode report API (markdown,
include_figure, include_table, save, new_report, render_report) or
an explicit report_t:
call new_report()
call markdown("# Results")
call plot(x, y)
call include_figure(caption="Simulation output.", label="fig:out", width="85%")
call clf()
call include_table(values, columns=[character(len=4) :: "t", "y(t)"], &
caption="Summary.", label="tab:res")
call markdown("See {numref}`fig:out` and {numref}`tab:res`.")
call save("report.pdf")
call save("report.svg") ! reuses cached layout
The layout is TeX’s (fplotlib_typeset), with LaTeX’s parameters and the
spacing of its article and book classes:
paragraphs are broken into lines by Knuth and Plass’s algorithm, TeX’s
line_breakwith its two passes, badness, demerits and fitness classes, and hyphenated with Liang’s algorithm and the patterns LaTeX and Typst use for English (hyph-en-us); interword glue is XeTeX’s for an OpenType font, and the space factor is\nonfrenchspacing’s;lines go onto a vertical list with
\baselineskip,\lineskipand TeX’s club, widow and broken penalties, and TeX’s page builder cuts it into pages at the breaks of least cost;displays get
\abovedisplayskipor the short skips, equation numbers at the right margin, and the paragraph goes on after them unindented.
A document goes through two layers: fplotlib_markdown parses a MyST subset
of Markdown and lays it out with LaTeX article or book spacing, setting it
twice, as LaTeX is run twice, so that the first pass numbers the sections and
equations every reference needs; and fplotlib_typeset implements
TeX’s primitives (words, glue, kerns, penalties, paragraphs, formulas, marks,
and the page builder).
The text is a strict MyST subset. TeX is confined to mathematics between $...$
and $$...$$. A display followed by (eq:name) is numbered, and
{eq}`eq:name` refers to it. A target (sec:name)= labels the block after
it; for a heading, {numref}`sec:name` writes “Section” and its number,
and {ref}`sec:name` writes its title; for a figure, {numref}`fig:name`
writes “Fig.” and its number, and {ref}`fig:name` writes its caption. As in
Sphinx, a role may give its own text, {ref}`the introduction <sec:name>` or
{numref}`Part %s <sec:name>`.
A reference that cannot be resolved is set as ?? with a warning, as LaTeX does.
A line break within a paragraph is a backslash at the end of the line (or,
in a single string, two spaces; typeset given an array of lines drops
their trailing blanks).
Vector plots can be embedded directly into a document without rasterization:
capture the current figure with call named_figure(figs(1), "name") (or
capture_figure(frame)), pass the array as figures=figs to typeset, and
place it in Markdown with :::{figure} name (supporting :width: in % or
any length unit, :align:, :name:, and the body as caption) or standalone
:
type(md_figure_t) :: figs(1)
call plot(x, y)
call named_figure(figs(1), "sine")
call typeset([character(len=80) :: &
"See {numref}`fig:sine`.", "", &
":::{figure} sine", ":width: 80%", ":name: fig:sine", &
"A sine wave.", ":::"], "report.pdf", figures=figs)
Front matter, between two lines of ---, holds the document options: title,
subtitle, author (or authors, one to a line, as a YAML list or repeated),
date, abstract, paper (a4, a5, a6, b5, letter, legal or
W x H), fontsize, linestretch, margin (and margin-left, -right,
-top, -bottom), indent, parskip, align, numbersections,
numberequations, chapters, pagenumbers, runningheads, flushbottom,
color and pagecolor. Lengths are PostScript points (1/72 in, pt and bp
alike), as in Typst, or pc, in, cm, mm, em or ex. A value that
cannot be read is warned of and leaves the default. Other keys are kept for
templates, which read them with md_meta.
The core sets the article layout, with optional chapter-based numbering
(chapters: true) and running-head placement (runningheads: true, drawing
marks set by a template with ts_mark). A template is
given to typeset as callbacks that receive the md_document_t first (with
its doc%engine public for ts_* calls): on_directive is given each MyST
directive, :::{name} argument with :key: value options and a body, as an
md_directive_t, and sets those it knows; on_heading is given each heading,
its level, text and number, as an md_heading_t, and sets those it wants set its
own way; and on_body adds what comes before and after the body. A callback that
sets a block says so in handled (.false. on entry); whatever it leaves is set
as the core sets it. A callback that sets blocks with md_blocks or sets a
nested document with md_typeset/typeset is declared recursive, and leaves
the outer document untouched. The gallery’s letter sets its sender, recipient
and closing so, with the room for the signature from its signature-skip, and
its invitation centres the card when the front matter says valign: center.
tests/para_refs.txt holds how XeTeX breaks seven paragraphs of Lato into
lines, read from its XDV output (tools/gen_para_refs.py), and fpm test
requires the same lines, hyphenated at the same places, with every glyph
within 0.07 bp (0.02 bp with Lato’s exact kerning, which fplotlib stores
to 5 font units). tools/compare_docs.py sets the gallery’s documents with
fplotlib, with LaTeX (Pandoc and Tectonic) and with Typst, with the same
fonts, and puts the pages side by side.
Using fplotlib in your project#
fplotlib is an fpm package with no dependencies
outside the Fortran standard library, so a project picks it up with one entry
in its fpm.toml:
[dependencies]
fplotlib = { git = "https://github.com/certik/fplotlib" }
and then use fplotlib and call plot, title, savefig as the examples below
do. It builds with gfortran, flang and LFortran:
fpm build --compiler gfortran
fpm build --compiler flang
fpm build --compiler lfortran
Errors#
A call that breaks a documented precondition is a bug in the calling
program, and it stops with a message naming the call and the rule, and
exit code 1: plot(alpha=1.5), savefig of an unknown format, xlim
with an infinite limit, or, below the plotting API, drawing on a canvas
that is not open or passing a nonfinite coordinate to a renderer. The
plotting procedures check their arguments as they come in: an alpha must
be in [0, 1], and a line width, marker size or font size must be finite
and not negative (matplotlib quietly accepts some negative sizes; here
they are taken for the mistakes they are). tools/gen_arg_checks.py
writes these checks from one table of every argument. The few upper
bounds there are, such as at most 10000 axes in a grid, are listed in the
fplotlib_status documentation.
Missing data is not such a bug: as in matplotlib, a NaN or an infinity in
plotted data is left out of the picture, and a line breaks around it. Data
far outside the view, such as a fill value of 1e30 under a ylim, is
clipped and drawn where it crosses the view.
A failure that a correct program can still meet at run time is returned
instead, through a status_t from fplotlib_status. Today that is an
output file that cannot be written, or a PNG cropped with
bbox_inches="tight" to more pixels than it can hold. savefig,
save_animation and the render_* functions return it in their optional
status, and without one stop with the message and exit code 2; so does
typeset, for the files of a document:
use fplotlib
type(status_t) :: st
call savefig("results/plot.png", status=st)
if (.not. st%ok()) print *, trim(st%message)
Frames and pages#
fplotlib_render:renderer_t is a drawing target, not a file writer; only
encoded_renderer_t, which the SVG, PNG, PDF and EPS backends extend, adds
bytes. A recording_renderer_t from fplotlib_scene records the drawing
into an owned frame_t instead, with no file or format.
fplotlib_draw:render_frame(frame) captures the current plot that
way, and fplotlib_mathtext:math_frame a formula. A frame’s
import_frame(child, handle) imports an owned copy;
place(handle, matrix, clip) can reuse it at several positions. The
six matrix entries are [a,b,c,d,e,f], mapping a point to
(a*x+c*y+e, b*x+d*y+f), and the optional rectangular clip is in the child’s
local coordinates. A paged_document_t holds pages of frames, which may have
different sizes; fplotlib_document exports it to bytes in memory
(export_document) or to files (save_document), one PDF or an SVG, PNG or
EPS per page. Glyph runs keep their logical UTF-8 text and the source byte
range of every glyph; PDF text carries a run’s text as ActualText, and a
formula keeps its TeX source, which is not used as ActualText.
Build#
The pixi tasks below are for developing fplotlib itself, with pinned compilers.
They require pixi. Every compiler has its own environment with
nothing in it but the compiler and fpm: gfortran and LFortran come from
conda-forge on Linux and macOS, flang on Linux (on macOS provide a system
flang on PATH). A task installs its environment the first time it runs.
pixi run test-gfortran # fpm test --compiler gfortran
pixi run test-gfortran-O3 # the same, built with -O3 -march=native
pixi run test-flang
pixi run test-flang-O3
pixi run test-lfortran
pixi run demo-flang # fpm run --example demo, writes demo.svg
# Compare the flang build against matplotlib references (needs Python,
# which lives in its own environment)
pixi run compare-all # all five below, sharing one build
pixi run compare # SVG, structurally
pixi run compare-png # PNG, pixel by pixel
pixi run compare-pdf # PDF, rasterized by pdftoppm
pixi run compare-eps # EPS, rasterized by ghostscript
pixi run compare-gif # GIF, frame by frame
# Build the documentation and run its Fortran gallery examples
pixi run gallery # HTML in docs/_build/html/
pixi run gallery-serve # build, then serve at http://127.0.0.1:8000 (Ctrl-C to stop)
The gallery has its own environment with Python, GFortran, and the documentation dependencies, including the gallery extension from this checkout.
Tests#
fpm test (or pixi run test-gfortran, test-flang, test-lfortran) writes every
test plot to tests/out/ and checks each PNG, and each frame of the GIF,
against a stored fingerprint in tests/fingerprints.txt. It needs nothing
outside the repository: no Python and no reference images.
A fingerprint is 4096 bits, 64 words of 64 bits, one word per tile of the
image, computed with integer arithmetic only (tests/test_fingerprint.f90).
Two builds of the same picture differ in a few bits per word, because
compilers round some antialiased edge pixels one level differently; a moved,
missing or recoloured element changes about half the bits of its tile’s word.
A case fails when any word differs by more than 10 bits, and the report says
where in the image:
FAIL clabel: 36 bits differ near x=80..160, y=120..180 (limit 10)
Measured on this suite, a tick moved by 1 px, a changed tick label or a one letter typo in a title changes a word by 18 to 40 bits, while a tick moved by 0.25 px or less passes. What the fingerprint cannot tell is whether a change is right, so after an intended change look at the new pictures (and run the matplotlib comparisons below), then store the new fingerprints:
fpm test -- --update
CI also runs the gfortran and flang tests built with -O3 -march=native
(pixi run test-gfortran-O3, test-flang-O3), where fused multiply-add
changes the rounding, so a picture that depends on the last bits of a
floating point value fails there.
The fingerprints cover the raster output. SVG, PDF and EPS are written by the same layout and drawing code but checked only by the comparisons below.
The SVG comparison is structural because a viewer, not fplotlib, decides what an SVG looks like. PNG, PDF and EPS are compared as pixels, since there fplotlib decides.
CI (Linux) has one job per compiler, each with only that compiler and fpm
installed, the compiler from fortran-lang/setup-fortran: gfortran, flang
and ifx are tested twice, the second time with -O3 -march=native so that
fused multiply-add is allowed and the pictures must not change; LFortran is
tested once. Each job also builds and runs the demo. ifx is given
-fp-model precise, because by default it reassociates, which turns a
linspace into a running sum and moves its endpoint and a contour grid’s
exactly-zero column by a few ulps. A separate job, on pixi, compares the
flang build against matplotlib.
Layout#
src/ library modules
fplotlib_state.f90 shared types and the figure state
fplotlib_artist.f90 drawing primitives (strokes, fills, markers)
fplotlib_draw.f90 layout, axes decoration, one renderer per plot type
fplotlib_typeset.f90 TeX's paragraph and page layout, for documents
fplotlib_markdown.f90 MyST Markdown set as LaTeX's article and book classes
fplotlib.f90 the plotting API
fplotlib_render.f90 the renderer contract the backends implement
fplotlib_status.f90 contract_error, and the status_t of calls that can fail
fplotlib_io.f90 writing a file, with the failure returned
fplotlib_scene.f90 owned frames, pages and a recording renderer
examples/ demo.f90
tests/ Fortran test plots, fingerprints, matplotlib refs, compare scripts
License#
The code is MIT, in LICENSE.
The generated glyph data in src/fplotlib_glyphs_data.f90 (outlines, metrics,
kerning and the math table) is OFL-1.1, derived from two fonts under the SIL
Open Font License 1.1: Lato, © tyPoland Łukasz Dziedzic with Reserved Font
Name “Lato” (LICENSE_LATO), and Lete Sans Math, © Chenjing Bu and Daniel
Flipo, built on Fira Math (© Xiangdong Zeng) and Lato (LICENSE_LETE). The
OFL is permissive: a program built with fplotlib ships the
OFL notice alongside the MIT one, and the plots fplotlib produces carry no
obligations. Because “Lato” is a Reserved Font Name, the fonts fplotlib
embeds in PDF and EPS files have names of their own: FplotlibSans-Regular,
FplotlibSans-Bold, FplotlibSans-Italic and FplotlibMath. tools/gen_glyphs.py regenerates the file from the pinned font
files. The hyphenation patterns in src/fplotlib_hyph_data.f90 are generated by
tools/gen_hyph.py from hyph-en-us.tex of the hyph-utf8 project, © Gerard
D.C. Kuiken, whose licence permits copying and distribution with or without
modification provided the copyright notice is kept, as it is in the file.
The colormap tables in src/fplotlib_cmap.f90 are sampled from matplotlib, which is
BSD-licensed, and the perceptual maps (viridis, magma, inferno, plasma) are
released by their authors under CC0.
Jupyter (LFortran)#
With LFortran as a Jupyter kernel, display the SVG interactively:
use fplotlib
use lfortran_display
! ... plot / title / grid / legend ...
call display_data("image/svg+xml", render_svg())
show() always writes fplotlib_show.svg (works with Flang and LFortran offline).
Fidelity to matplotlib#
fplotlib is measured against matplotlib rather than described as similar to it:
every feature has a case in tests/test_plots.f90 and a matplotlib reference
in tests/gen_mpl_refs.py, and the comparisons above put a number on the
difference. As of this writing, over 100 cases:
format |
cases |
mean difference |
|---|---|---|
PNG |
126 |
1.31/255 |
125 |
0.93/255 |
|
EPS |
126 |
2.28/255 |
GIF |
20 frames |
0.39/255 |
The references are made with matplotlib set to the same Lato files fplotlib’s glyphs come from. What is left is mostly antialiasing along edges, and text: fplotlib fills the outlines unhinted where matplotlib hints them through FreeType, so a stem lands on the same pixel column as matplotlib’s but not always with the same coverage. The SVG is not matplotlib’s SVG byte for byte, and is not meant to be: both write every glyph as a path, but matplotlib attaches its own ids and metadata.
Math is the exception: matplotlib’s mathtext is its own approximation of TeX,
and fplotlib follows TeX itself, so the formulas are checked against XeTeX
instead. tests/math_refs.txt holds where XeTeX (Tectonic, with
unicode-math and the same font files) puts every glyph and rule of 92
formulas, and fpm test requires fplotlib to put each within 0.02 pt of it.
The automatic delimiters, which TeX does not have, are checked against
Typst’s in tests/delim_refs.txt. Both files are regenerated with pixi,
nothing installed system-wide:
pixi exec --spec tectonic --spec pdfminer.six --spec fonttools \
--spec python=3.12 -- python tools/gen_math_refs.py
pixi exec --spec typst --spec pdfminer.six --spec fonttools \
--spec python=3.12 -- python tools/gen_delim_refs.py