cogra
GitHub

API reference

Every public function, from its signature and docstring. import cogra registers the fonts and styles; the geoms are in cogra.geoms, the wear looks in cogra.wear, and papers in cogra.paper.

Styles

cogra.use(labels: Literal['sans', 'serif'] = 'sans', size: str | None = None) -> None
Apply the style; the same as plt.style.use(["cogra", ...]). labels: 'sans' (stencil/phototype look, as in 1980s PDP figures) or 'serif' (the cogra body face). size: None, 'column' (2.65 in, one column of a cogra.paper page) or 'page' (5.46 in, across both).

source

cogra.register_fonts() -> None
Add TeX Gyre Heros and Schola to matplotlib's font list (once).

source

cogra.register_styles() -> None
Make the cogra styles available by name to plt.style.use and plt.style.context: cogra, cogra-serif, cogra-column, cogra-page. Runs on import cogra, as SciencePlots does for its styles.

source

Restyling finished figures

cogra.restyle(fig: Figure, labels: Literal['sans', 'serif'] = 'sans', despine: bool = True) -> Figure
Restyle a finished figure in place and return it. Also applies the cogra rcParams globally (via use), so later figures match.

source

class cogra.cogra(**kw)
Pipe-style application: fig | cogra() (mirrors p + cogra() in R).

source

Period plots

cogra.bars(ax: Axes, x: ArrayLike, heights: ArrayLike, hatches: Sequence[str] | None = None, **kw: Any) -> BarContainer
Bar chart in period style: white fill, black outline, hatching to tell conditions apart. matplotlib otherwise fills bars with the line colour (black), which the style file cannot change separately.

source

cogra.violin(ax: Axes, datasets: Sequence[ArrayLike], positions: ArrayLike | None = None, hatches: Sequence[str] | None = None, width: float = 0.7, bw: float | None = None, median: bool = True, side: Literal['both', 'left', 'right'] = 'both') -> Axes
Outlined violins with hatching instead of fill colour. side: 'both', 'left' or 'right' (half violins, used by raincloud). A dataset with no spread is drawn as a single horizontal rule.

source

cogra.raincloud(ax: Axes, datasets: Sequence[ArrayLike], positions: ArrayLike | None = None, hatches: Sequence[str] | None = None, seed: int = 0, width: float = 0.6) -> Axes
Half violin (cloud), slim box plot, and jittered open circles (rain).

source

cogra.topoplot(ax: Axes, xy: ArrayLike, values: ArrayLike, levels: int | ArrayLike | None = None, hatch: bool = True, labels: bool = True, electrodes: bool = True, res: int = 200, fmt: str = '%g') -> ContourSet | None
Scalp map in contour-and-hatching form. xy: (n, 2) electrode positions scaled so the head is the unit circle (nose at +y). values: n values. Negative contours are dashed. Returns the ContourSet, or None if the map is flat (no contours).

source

cogra.density_topo(ax: Axes, x: ArrayLike, y: ArrayLike, masses: Sequence[float] | None = None, index: Sequence[float] = (0.5, 0.9), points: bool | Literal['outside'] = True, bw: float | None = None, res: int = 220, pad: float = 0.15, point_size: float = 1.5, label_fmt: str = '{:.0%}') -> ContourSet
Scatter with kernel density contours drawn like a topographic map. Contours enclose fixed fractions of the probability mass (highest- density regions): the 50% line encloses the densest half of the distribution. Lines in `index` are drawn heavier and labelled, like index contours on a survey map; the rest are thin and unlabelled. Note these are fractions of the estimated density, not exact fractions of the plotted points. points: True (all points), False (none), or "outside" (only points beyond the outermost contour, which keeps large samples readable).

source

cogra.halftone(ax: Axes, cx: ArrayLike, cy: ArrayLike, values: ArrayLike, cell_w: float, cell_h: float, vmin: float | None = None, vmax: float | None = None, shape: Literal['circle', 'square'] = 'circle', **kw: Any) -> Collection
Add a HalftoneCollection to ax. cx, cy: cell centres (any shape); values: one per cell (NaN = no dot); cell_w, cell_h: cell size in data units. Extra keywords (zorder, label, ...) go to the collection.

source

Significance

cogra.signif(ax: Axes, x1: float, x2: float, p: float | None = None, text: str | None = None, show: Literal['stars', 'p'] = 'stars', ns: bool = False, y: float | None = None, pad: float = 0.04, tick: float = 0.02, fontsize: float | None = None, linewidth: float = 0.8, levels: Sequence[tuple[float, str]] = ((0.001, '***'), (0.01, '**'), (0.05, '*'))) -> tuple[Line2D, Text] | None
A significance bracket from x1 to x2 with stars above it. p: the p value, labelled with stars (show="stars", the default) or as 'p = .012' (show="p"). text: your own label instead ("n.s.", "d = 0.54"). ns: with stars, a p that is not significant draws nothing unless ns=True, which writes "n.s.". y: where the bracket sits; by default just above the highest thing between x1 and x2 (bars, error bars, points, earlier brackets), so several brackets stack. pad and tick are fractions of the y range. Call it after the data are drawn. Returns (line, text), or None when nothing is drawn. The bracket never changes the x limits; the y limit grows if the label would otherwise be cut off.

source

cogra.stars(p: float, levels: Sequence[tuple[float, str]] = ((0.001, '***'), (0.01, '**'), (0.05, '*'))) -> str
'***', '**', '*' or '' for a p value (thresholds are exclusive: p < .05). Raises ValueError for a p outside [0, 1] or NaN.

source

cogra.format_p(p: float) -> str
APA-style p with an italic p and no leading zero: 'p < .001', 'p = .012'. Raises ValueError for a p outside [0, 1] or NaN.

source

Worn copies

cogra.save_vintage(fig: Figure, path: str | os.PathLike[str], look: Literal['scan', 'xerox', 'aged'] = 'scan', dpi: int = 600, scan_dpi: int = 300, strength: float = 1.0, weight: float = 1.0, fade: float | None = None, generations: int = 2, seed: int = 1956, specks: bool = False, cache: bool = True) -> Path
Render fig at `dpi`, apply wear, save as PNG (or anything PIL writes). The scan look writes a 1-bit image at scan_dpi. specks defaults to False for figures: random dust specks are indistinguishable from data points in a scatter plot. cache: True keeps worn images in cache_dir(), keyed by the rendered figure and every setting, so re-running an unchanged figure skips the wear. False turns it off; a path uses that folder.

source

cogra.cache_dir() -> Path
Where save_vintage keeps worn images: $COGRA_CACHE, else $XDG_CACHE_HOME/cogra, else ~/.cache/cogra.

source

cogra.clear_cache() -> None

source

The wear looks

cogra.wear.apply(gray: NDArray[np.uint8], look: Literal['scan', 'xerox', 'aged'] = 'scan', dpi: int = 600, scan_dpi: int = 200, strength: float = 1.0, weight: float = 1.0, fade: float | None = None, generations: int = 2, skew: float = 0.0, paper: str = 'aged', specks: bool = True, seed: int = 1956) -> tuple[Image.Image, int]
Run one look and return (PIL image, output dpi).

source

cogra.wear.scan(gray: NDArray[np.uint8], dpi: int = 600, scan_dpi: int = 200, strength: float = 1.0, weight: float = 1.0, skew: float = 0.0, specks: bool = True, seed: int = 1956, tile: int = 256) -> NDArray[np.bool_]
Bilevel scan. Work at render resolution, then area-average down to scan_dpi and threshold, which gives the stair-stepped edges. A noise field at roughly letter scale shifts the threshold so some glyphs come out heavier than their neighbours. Returns a bool array, True = white.

source

cogra.wear.xerox(gray: NDArray[np.uint8], dpi: int = 600, strength: float = 1.0, fade: float = 0.25, generations: int = 2, skew: float = 0.0, specks: bool = True, seed: int = 1956, tile: int = 256) -> NDArray[np.uint8]
Photocopy look. Each generation re-thresholds a slightly blurred copy, which thickens strokes and fills in counters the way repeated copying does. Returns uint8 grayscale.

source

cogra.wear.aged(gray: NDArray[np.uint8], dpi: int = 600, strength: float = 1.0, fade: float = 0.35, paper: str = 'aged', specks: bool = True, seed: int = 1956, tile: int = 256) -> NDArray[np.uint8]
Original letterpress page on toned paper. Returns uint8 RGB.

source

ggplot2-style geoms

cogra.geoms.geom_point(ax, x, y, group=None, size=5, **kw)

source

cogra.geoms.geom_jitter(ax, x, y, group=None, width=0.15, height=0.0, seed=0, size=4, **kw)

source

cogra.geoms.geom_count(ax, x, y, max_size=12, **kw)
Open circles sized by the number of overlapping observations.

source

cogra.geoms.geom_line(ax, x, y, group=None, markers=False, **kw)

source

cogra.geoms.geom_path(ax, x, y, group=None, **kw)
Like geom_line but joins points in data order.

source

cogra.geoms.geom_step(ax, x, y, group=None, where='post', **kw)

source

cogra.geoms.geom_abline(ax, intercept=0, slope=1, **kw)

source

cogra.geoms.geom_hline(ax, yintercept, **kw)

source

cogra.geoms.geom_vline(ax, xintercept, **kw)

source

cogra.geoms.geom_segment(ax, x, y, xend, yend, arrow=False, **kw)

source

cogra.geoms.geom_curve(ax, x, y, xend, yend, curvature=0.3, arrow=True, **kw)

source

cogra.geoms.geom_spoke(ax, x, y, angle, radius, **kw)

source

cogra.geoms.geom_function(ax, fun, xlim=None, n=200, **kw)

source

cogra.geoms.geom_rug(ax, x=None, y=None, length=0.03, **kw)

source

cogra.geoms.geom_area(ax, x, y, group=None, stacked=True, **kw)
Hatched areas; stacked by default, as in ggplot2.

source

cogra.geoms.geom_ribbon(ax, x, ymin, ymax, hatch='....', outline=True, **kw)

source

cogra.geoms.geom_rect(ax, xmin, xmax, ymin, ymax, group=None, **kw)

source

cogra.geoms.geom_polygon(ax, polygons, group=None, **kw)
polygons: list of (n, 2) arrays.

source

cogra.geoms.geom_col(ax, x, height, group=None, width=0.7, dodge=True, **kw)
Bars of given height. With groups, bars are dodged side by side.

source

cogra.geoms.geom_bar(ax, x, group=None, **kw)
Counts of each category, like geom_bar(stat='count').

source

cogra.geoms.geom_histogram(ax, x, group=None, bins=30, **kw)
Outlined bars; overlapping groups are drawn as step outlines with hatching.

source

cogra.geoms.geom_freqpoly(ax, x, group=None, bins=30, **kw)

source

cogra.geoms.geom_density(ax, x, group=None, hatch=False, bw=None, n=256, **kw)

source

cogra.geoms.geom_dotplot(ax, x, binwidth=None, dot_scale=1.0, **kw)
Wilkinson dot plot: values binned and stacked as open circles. Dots are drawn in data units, so set the y range to suit.

source

cogra.geoms.geom_boxplot(ax, datasets, positions=None, width=0.5, hatches=None, outliers=True, **kw)
Tukey box plots: whiskers to 1.5 IQR, outliers as open circles.

source

cogra.geoms.geom_violin(ax, datasets, positions=None, **kw)

source

cogra.geoms.geom_errorbar(ax, x, ymin, ymax, width=0.15, orientation='x', **kw)
orientation='y' gives horizontal bars (the replacement for geom_errorbarh, deprecated in ggplot2 4.0.0).

source

cogra.geoms.geom_errorbarh(ax, y, xmin, xmax, height=0.15, **kw)
Deprecated in ggplot2 4.0.0; kept as an alias for orientation='y'.

source

cogra.geoms.geom_linerange(ax, x, ymin, ymax, **kw)

source

cogra.geoms.geom_pointrange(ax, x, y, ymin, ymax, group=None, **kw)

source

cogra.geoms.geom_crossbar(ax, x, y, ymin, ymax, width=0.4, group=None, **kw)

source

cogra.geoms.geom_smooth(ax, x, y, method='loess', se=True, level=0.95, span=0.75, n=100, **kw)
method='lm': OLS line with a confidence band (dashed bounds over stippling). method='loess': local linear fit (degree 1, tricube weights). For loess, se=True gives a bootstrap band (200 resamples), which differs from ggplot2's analytic loess interval.

source

cogra.geoms.geom_quantile(ax, x, y, quantiles=(0.25, 0.5, 0.75), **kw)
Linear quantile regression, solved exactly as a linear program.

source

cogra.geoms.geom_qq(ax, sample, dist='norm', **kw)

source

cogra.geoms.geom_qq_line(ax, sample, dist='norm', **kw)
Line through the first and third quartiles, as in ggplot2.

source

cogra.geoms.geom_density_2d(ax, x, y, levels=8, bw=None, **kw)

source

cogra.geoms.geom_density_2d_filled(ax, x, y, levels=6, bw=None, **kw)

source

cogra.geoms.geom_contour(ax, X, Y, Z, levels=8, labels=True, **kw)

source

cogra.geoms.geom_contour_filled(ax, X, Y, Z, levels=6, lines=True, **kw)
Bands hatched more densely at higher levels; the lowest band is left white.

source

cogra.geoms.geom_bin_2d(ax, x, y, bins=20, **kw)
Rectangular bins drawn as halftone squares.

source

cogra.geoms.geom_hex(ax, x, y, gridsize=18, **kw)
Hexagonal bins drawn as halftone dots at the hexagon centres.

source

cogra.geoms.geom_tile(ax, x, y, value, width=1.0, height=1.0, **kw)
Tiles at (x, y) with halftone dots sized by value, plus a light grid.

source

cogra.geoms.geom_raster(ax, Z, extent=None, **kw)
Regular grid of values as halftone dots, no cell outlines.

source

cogra.geoms.geom_text(ax, x, y, labels, **kw)

source

cogra.geoms.geom_label(ax, x, y, labels, **kw)

source

cogra.geoms.geom_map(ax, polygons, values=None, classes=4, **kw)
Choropleth: polygons hatched by value class (denser = higher). polygons: list of (n, 2) coordinate arrays, one per region.

source

cogra.geoms.geom_sf(ax, geometries, values=None, classes=4, **kw)
Simple-features layer. Accepts shapely Polygon/MultiPolygon objects (or a GeoSeries) and draws them like geom_map. shapely is only needed if you pass shapely objects.

source

cogra.geoms.geom_sf_text(ax, polygons, labels, **kw)

source

cogra.geoms.geom_sf_label(ax, polygons, labels, **kw)

source

cogra.geoms.geom_blank(ax, *args, **kw)
Draws nothing, as in ggplot2 (useful for setting limits).

source

Papers

class cogra.paper.Paper(title, authors=(), affiliations=(), abstract='', keywords='', author_note=(), masthead='', first_page_foot='', running_head=None, short_authors=None, blocks=(), footnotes=None, figures=None, columns=2, style=None, css=(), worn=True, start_page=1, note='', lang='en', apply_title_case=True)
A paper laid out as an APA journal article of about 1980. title, authors, affiliations: the title block. Authors and affiliations are strings or lists of strings; '^1' marks become superscripts. abstract: HTML (or Markdown via from_markdown), set across the measure. keywords: optional line under the abstract. author_note: paragraphs for the foot of the first column (grants, acknowledgments, correspondence). masthead: top-left lines on the first page (journal, volume, pages). first_page_foot: centred line at the foot of the first page. running_head / short_authors: running heads on right- and left-hand pages. blocks: the body as source HTML elements, in order (from_markdown makes these); footnotes: {number: html}. figures: {name: matplotlib Figure or image path}, used by blocks made with figure_block(), and by '![caption](fig:name)' in Markdown. columns: 2 (default) or 1. style: {custom property: value} overrides, e.g. {"body": "10pt", "page-w": "612pt", "page-h": "792pt"} (see apa1980.css for the list). css: extra stylesheet paths, loaded after the default one. worn: True for the archival-scan look (default), False for clean type. start_page: number on the first page. note: HTML shown above the pages on screen (not printed).

source

cogra.paper.Paper.from_markdown(source: str | os.PathLike[str], base_dir: str | os.PathLike[str] | None = None, figures: Mapping[str, Figure | str | os.PathLike[str]] | None = None, small_sections: Sequence[str] = ('Method', 'Methods'), omit_headings: Sequence[str] = ('Introduction',), small_caps: Sequence[str] = ('ANOVA', 'MANOVA'), **overrides: Any) -> Paper
Build a Paper from Markdown with a YAML front matter block. source: a path or the Markdown text. base_dir: where relative image paths are looked up (the file's folder by default). Keyword arguments override front-matter fields.

source

cogra.paper.Paper.save(out_dir: str | os.PathLike[str], worn: bool | None = None, controls: bool = True) -> Path
Write the page and its assets to out_dir; returns the index.html path.

source

cogra.paper.Paper.pdf(path: str | os.PathLike[str], worn: bool | None = None, engine: Literal['auto', 'playwright', 'chrome'] = 'auto', timeout: float = 120) -> Path
Print the paginated pages to a PDF. engine: 'auto', 'playwright' or 'chrome'. With worn=True (the default for a worn Paper) text is printed as an image and is not searchable; worn=False gives clean, searchable type.

source

cogra.paper.Paper.html(worn: bool | None = None, controls: bool = True, fig_files: dict | None = None) -> str
The page as one HTML string (asset paths relative to its folder).

source

cogra.paper.find_chrome() -> str | None
A Chrome-family browser for headless printing, or None.

source

cogra.paper.title_case(s: str) -> str
Title case as APA journals of the period set it. Words that already contain capitals (SSRT, fMRI) are left alone.

source