Introduction¶
What is PyX?¶
PyX is a Python package for creating publication-quality graphics in PostScript, PDF, and SVG formats. It combines a clean Pythonic abstraction of the PostScript drawing model with seamless TeX/LaTeX integration and native Type 1 and OpenType font handling.
The design of PyX is guided by several core principles:
Programmatic precision: Figures are described in Python code rather than assembled interactively in a GUI. This makes complex or data-driven figures reproducible, parameterizable, and easy to maintain alongside scientific or engineering code.
Unified drawing primitives: Geometric shapes are represented as math-aware PostScript-like paths (
pathandnormpath) or MetaPost-like spline paths (metapost.path) that support intersections, arc-length parameterization, tangents, curvatures, and geometric deformations (deformer).Composable canvases and attributes: Graphics primitives are collected on hierarchically nestable canvases (
canvas) and styled through a typed, composable attribute system (attr,style,deco,color,pattern,trafo).First-class typography: Text can be typeset through an interactive TeX or LaTeX subprocess (
text.TexEngine,text.LatexEngine) so that mathematical formulas and document fonts match your manuscript, or rendered directly viatext.UnicodeEngineusing Type 1 or OpenType fonts without invoking TeX.Modular plotting architecture: High-level components such as 2D and 3D graphs (
graph) and axes (graph.axis) are built directly on top of PyX’s path, canvas, and text primitives, with clear interfaces for custom data sources, plot styles, axis partitioners, texters, and painters.
A first example¶
To see how these concepts fit together, consider a minimal script that draws a stroked red rectangle and typesets a centered mathematical expression inside it:
from pyx import *
c = canvas.canvas()
c.stroke(path.rect(0, 0, 4, 2), [style.linewidth.Thick, color.rgb.red])
c.text(2, 1, r"$\int_{-\infty}^\infty e^{-x^2}\,\mathrm{d}x = \sqrt{\pi}$",
[text.halign.center, text.valign.middle])
c.writeEPSfile("hello")
c.writePDFfile("hello")
c.writeSVGfile("hello")
Here canvas.canvas() creates an drawing surface, path.rect(0, 0, 4, 2)
constructs a rectangular path of width 4 cm and height 2 cm (using PyX’s default
user unit of centimeters), and the attribute list [style.linewidth.Thick,
color.rgb.red] specifies how the path is stroked. Finally, writeEPSfile,
writePDFfile, and writeSVGfile write the canvas to hello.eps,
hello.pdf, and hello.svg.
Organization of this manual¶
This manual is organized both as a progressive guide for new users and as a complete technical reference for experienced PyX users and developers:
Basic graphics (Basic graphics, Paths, MetaPost-like paths, Deformers, Canvas, Documents): Introduces the drawing model, the attribute system (
attr), stroke and fill styles (style), path decorators (deco), path construction and normalized path geometry (path,normpath,metapost), path deformers (deformer), canvases (canvas), and multi-page documents (document).Text (Text): Covers text typesetting with TeX, LaTeX, and
text.UnicodeEngine, text alignment and sizing attributes, color and transformation handling, markers, and diagnostics.Plotting (Graphs, Axes): Describes 2D and 3D data plotting, data sources (
graph.data), plotting styles (graph.style), graph keys (graph.key), and the axis system (graph.axis,graph.axis.parter,graph.axis.texter,graph.axis.painter,graph.axis.rater,graph.axis.tick).Boxes and Connectors (Module box: Convex box handling, Module connector): Explains aligned polygonal and rectangular boxes and the connectors linking them.
External graphics and bitmaps (Module epsfile: EPS file inclusion, Module pdffile: PDF file inclusion, Module svgfile: SVG file inclusion, Bitmaps): Covers embedding EPS, PDF, SVG, and raster bitmap images.
Basic classes and modules (Module bbox, Module color, Module pattern, Module unit, Module trafo: Linear transformations): Documents bounding boxes, color spaces and gradients, fill patterns, the multi-scale unit system, and affine transformations.
Appendix: Provides visual catalogs of predefined colors, gradients, path styles, arrows, and internal utility helpers.
Note
Throughout this manual, classes and functions that accept geometric coordinates
or lengths in PyX units (which support unit scaling and explicit units such as
2*unit.t_cm) often have a companion class or method ending in _pt
(such as path.line_pt or canvas.canvas.text_pt()). These
_pt variants take numerical values directly in PostScript points
(1 pt = 1/72 inch) and bypass unit conversion for performance-critical
internal and developer code.
Installation¶
Prerequisites¶
PyX requires Python 3. When using the default TeX/LaTeX text engines
(text.TexEngine and text.LatexEngine), a working TeX
installation (such as TeX Live or MiKTeX) with Type 1 fonts is required. If you
use text.UnicodeEngine exclusively with shipped or local Type 1 /
OpenType fonts, PyX can generate PostScript, PDF, and SVG output without invoking
an external TeX interpreter.
To include or manipulate raster images beyond uncompressed PNM or JPEG files, the Python Imaging Library (Pillow) is optional but recommended.
Installing PyX¶
The easiest way to install the latest release of PyX is via pip:
pip install pyx
To install PyX from a source distribution or a Git checkout, run:
pip install .
from the top-level directory of the source tree.
By default, PyX installs as a pure Python package and locates TeX files and
fonts by invoking the kpsewhich command-line tool. For faster file lookup in
environments with frequent font searches, PyX also includes an optional C
extension module, pykpathsea, which links directly against libkpathsea.
You can enable building pykpathsea by editing setup.cfg prior to
installation and specifying the appropriate include and library paths for your
TeX distribution.
Configuration and file location¶
Runtime configuration (pyxrc)¶
PyX reads its runtime configuration from a sequence of INI-style configuration files:
The built-in default configuration
pyx/data/pyxrcshipped with PyX.A user-specific configuration file:
~/.pyxrcon Unix/macOS systems, or%APPDATA%\pyxrcon Windows.Any configuration file specified by the environment variable
PYXRC.
Settings in later files override earlier ones. The configuration is divided into three sections:
[general]space(defaultSPACE): Whitespace-separated list options inpyxrcuse this token to represent literal space characters inside list items.
[text]defaulttextengine(defaultTexEngine): Default text engine class initialized intext(TexEngine,LatexEngine, orUnicodeEngine).tex(defaulttex): Command (and optional whitespace-separated arguments) used to start the plain TeX interpreter.latex(defaultlatex): Command (and optional whitespace-separated arguments) used to start the LaTeX interpreter.psfontmaps(defaultpsfonts.map): Whitespace-separated list of font mapping files used for PostScript and SVG output.pdffontmaps(defaultpdftex.map): Whitespace-separated list of font mapping files used for PDF output.wait(default60): Maximum time in seconds to wait for a response from the TeX/LaTeX subprocess before raising a timeout error.showwait(default5): Interval in seconds between progress warnings logged while waiting for TeX/LaTeX (set to0to disable).texipc(default0): Boolean flag enabling TeX’s--ipcoption for reading DVI pages before TeX terminates.chrootandtmpdir: Optional path overrides for running TeX inside a chroot environment or a custom temporary directory.
[filelocator]methods(defaultlocal internal pykpathsea kpsewhich): Whitespace-separated list of file lookup methods tried in order when PyX searches for fonts, metrics, headers, or figures:local: Searches the current working directory.internal: Searches thepyx/datapackage resources shipped with PyX (such as built-in.lfsfiles,pyxrc, and standard AFM/Type 1 files).recursivedir: Recursively searches the directories listed in therecursivediroption of[filelocator].ls-R: Searches TeXls-Rfilename databases listed in thels-Roption of[filelocator].pykpathsea: Uses the compiledpykpathseaC extension if available.kpsewhich: Calls thekpsewhichexecutable (customizable via thekpsewhichoption in[filelocator]).locate: Calls the systemlocatecommand (customizable via thelocateoption in[filelocator]).
Developer interface: config and logging¶
For PyX developers, the config module provides programmatic access to configuration settings, resource discovery, and subprocess execution:
- config.get(section, option, default=...)¶
- config.getint(section, option, default=...)¶
- config.getfloat(section, option, default=...)¶
- config.getboolean(section, option, default=...)¶
- config.getlist(section, option, default=...)¶
Retrieve an option from section as a string, integer, float, boolean, or whitespace-split list of strings. If default is provided, it is returned whenever the section or option is not present in the configuration.
- config.open(filename, formats, ascii=False)¶
Locate and open filename by trying the configured
[filelocator]methods for the given list offormatspecifications. Returns a binary stream by default, or a text stream withasciiencoding andsurrogateescapeerror handling when ascii isTrue. RaisesIOErrorif the file cannot be found.Standard file formats defined on
formatare:format.tfm(.tfm)format.afm(.afm)format.pfm(.pfm)format.fontmap(.map)format.pict(.eps,.epsi)format.tex_ps_header(PostScript headers and.encencoding files)format.type1(.pfa,.pfb)format.vf(.vf)format.dvips_configformat.ttf(.ttf,.ttc,.TTF,.TTC,.dfont)format.t42(.t42,.T42)format.otf(.otf)format.pyx(internal PyX data files)
PyX uses Python’s standard logging module to report warnings and
diagnostic information:
logging.getLogger("pyx"): Main logger used for warnings across all PyX modules.logging.getLogger("pyx.execute"): Logs external subprocess invocations (such astex,latex,kpsewhich, orgs) at theINFOlevel.logging.getLogger("pyx.filelocator"): Logs every file lookup and its resolved path at theINFOlevel.
To inspect which external commands and font files PyX uses during a run, enable
INFO logging in your script:
import logging
logging.basicConfig(level=logging.INFO)