Skip to main content

hairline

Clean, predictable figures for medical and data science. One frame for titles, legends, panels and captions, one type scale, colour-vision checked palettes, and print-ready files. The R package of the same name draws the same figures from the same design tokens, so a Python figure and an R figure in one manuscript match.

pip install hairline

The development version, with changes not yet released (see the changelog), installs from GitHub: pip install "hairline @ git+https://github.com/schradern/hairline#subdirectory=python".

Python 3.11 or later, matplotlib 3.11 or later: from 3.11 matplotlib kerns text as R does, so both packages place every label alike. The bundled font, Hairline Sans, needs no installation.

ICU bed occupancy in small multiples, drawn with hairline

From data to a result

Most studies need the same few results: a cohort description, a comparison between groups, effects, events over time. study() takes a data frame once, with the role of each column, checks the data, and returns each result as a figure, a table, the key values and a sentence for the text.

import numpy as np
import pandas as pd
import hairline as hl

rng = np.random.default_rng(1)
cohort = pd.DataFrame({
    "arm": np.repeat(["Standard care", "Early mobilisation"], 40),
    "age": rng.normal(64, 12, 80).round(),
    "sex": rng.choice(["Female", "Male"], 80),
    "months": rng.exponential(20, 80).round(1),
    "died": rng.binomial(1, 0.4, 80),
})
study = hl.study(cohort, group="arm", time="months", event="died",
                 units={"age": "years", "months": "months"})

table_one = study.describe()     # Table 1: median (IQR) and n (%) per group
table_one.table                  # a data frame
age = study.compare("age")       # spread rows per group, Wilcoxon rank-sum
age.text                         # "Age (years), median (IQR): ... (Wilcoxon rank-sum, p = ...)."
age.numbers["test"]["p"]         # the unrounded p the text formats
survival = study.survival()      # Kaplan–Meier with numbers at risk and the log-rank test
hl.save(survival.figure, "survival")              # survival.pdf and survival.png

Printing a study lists its checks: missing values, duplicate ids, categories that differ only in case, small groups, numeric columns without a unit. Errors stop the analysis; warnings name the fix. With id=, describe(), compare() and distribution() refuse a variable with more than one row per id, so repeated measurements are not counted as separate patients.

Charts

Each chart is one call with the data and its column names, and returns a figure in the hairline frame: bars, scatter, timeseries, spread, raincloud, ridgeline, kaplan_meier, forest, dotplot, funnel, correlation, donut, partition, waffle, sankey, chord, arcs, venn, prisma, risk_of_bias, lanes, levels, swimlanes, process, likert, heatmap, surface and table.

admissions = pd.DataFrame({"diagnosis": ["Sepsis", "Sepsis", "Trauma", "Cardiac", "Cardiac"],
                           "sex": ["Female", "Male", "Male", "Female", "Male"]})
figure = hl.bars(admissions, "diagnosis", by="sex", subtitle="Admissions, 2025")
hl.save(figure, "admissions", formats=["pdf", "png", "svg", "html"])

For anything else, hl.figure() gives the same frame around your own matplotlib axes:

figure = hl.figure("Lactate falls after admission", subtitle="Mean per day", size="single")
figure.ax.plot([0, 1, 2, 3], [4.1, 3.2, 2.6, 2.2], label="All patients")
figure.y_title("mmol/l")
hl.save(figure, "lactate")

For reports

What a real report needs is one argument on the chart, and the caption says in the figure's locale what was left out or drawn differently ("Unvollständig, heller: 2021 (2 Monate)", "Not shown (under 10): …").

hl.bars(cases, "year", "cases", facet="procedure", scales="free", columns=2,   # one panel per procedure
        partial={"2021": "2 months", "2026": "10 months"})                     # incomplete years drawn lighter
hl.bars(locations, "place", facet="procedure", top=6)                          # the rest as one "Other" bar
hl.bars(patterns, "procedure", by="pattern", stacked=True, normalize=True)     # shares from counts, n kept
hl.spread(doses, "procedure", "mg", show_n=True, min_n=10, clip=0.99,          # n, small groups out, outliers
          stats=("median", "levels"), discrete=True)                           # the frequent doses, on levels
hl.bars(cases, "year", by="row", color_by="procedure")                         # 12 rows, 4 colours
with hl.scope("pattern"):                                                      # off the procedures' slots
    hl.bars(patterns, "pattern")
  • facet=, scales=, columns= on bars: one panel per value, each with its own value axis or one shared axis, the panel header with the facet's total. top= and other= fold the smallest categories.
  • partial= on bars and timeseries: incomplete periods drawn lighter, named in the caption.
  • show_n= on bars, spread and ridgeline (n= column on dotplot): the n after the label or in the numbers column; colours and order keep keying on the bare group.
  • min_n= on spread, ridgeline and raincloud; clip= (a quantile, or (low, high)) on those and scatter. The statistics use every value unless clip_stats=True.
  • margins="mean" (or "sum", for counts) on heatmap: each column's mean in a bar above it and each row's in a bar to its right, the largest of each written at its end.
  • density=True on scatter: the points counted in hexagons, coloured by count and keyed in the legend row, for clouds too dense to read point by point; a number sets the hexagons across.
  • color_by= on every chart with groups, dimension= or hl.scope() across figures.
  • stats=("levels", …) and discrete=True on spread: the most frequent values with their shares, and quantiles on the data's own levels. spread() and describe() warn when a median falls between two large levels and matches neither.
  • hl.table(frame, …): any frame (or describe().table) in hairline's typography, numbers in the locale, bold_rows=, footnotes=, saved as PDF, PNG, SVG and as a real HTML table.
  • hl.report(): figures and tables numbered in the locale ("Abbildung 1", "Tabelle 2") in one Markdown or HTML file with everything embedded. In HTML the figures are interactive and linked: pointing at a group in one highlights the same group in every other.

Over the time of day

figure = hl.figure("Occupancy and staffing", panels=3, heights=(9, 3, 4), sharex=True, size="double")
hl.lanes(stays, "place", "start", "end", group="section", days="weekdays", flows=moves,
         spans={"Regular hours": (7, 16)}, into=figure, panel=0)
hl.levels(staff, "start", end="end", by="role", days="weekdays", into=figure, panel=1)
hl.save(figure, "unit_day")
  • lanes(): one row per place, each 15-minute cell coloured by the share of days it was occupied, in its section's ramp, binned as the key in the legend row (HairlineFigure.legend_ramp()); flows= adds the moves between rows as faint connectors.
  • levels(): whole counts of people as steps: how often exactly 1, 2, 3 … were needed, the typical day and the count that is enough on 9 of 10 days, on the data's levels (R's quantile type 1).
  • swimlanes(): one real day, a bar per interval with its label inside where it fits, an inner interval as a darker band, and assign="first_free" to turn tasks into rows of people.
  • process(): a procedure in swimlanes, one lane per role, steps left to right in stages and flows handing on from step to step, labelled where they leave. status= highlights what changed and dashes what is absent or open, note= numbers a step and lists its text below the lanes, section= stacks versions (before, after) on the same lanes.
  • figure(heights=, sharex=, sharey=) sizes panel rows by content on one x axis; time_axis() labels the hours ("06", "08") cropped to the data, with named spans.

Surveys

hl.likert(survey, "statement", "rating", levels=range(1, 11), group="section",  # 1–2, 3–5 | 6–8, 9–10
          reverse=["Waited too long on the day"])                               # recoded and marked
hl.spread(importance, "feature", "rating", section="area", panel_letters=True,  # a, b, c blocks
          mean=True, sort="median")                                             # mean as an open diamond
hl.bars(sources, "answer", facet="question", respondents="respondent",          # % of respondents, n per panel
        context=["None of these"], header="n")                                  # the exclusive answer in grey
hl.bars(answers, "question", "count", by="answer", stacked=True, percent=True,  # each answer named inside,
        inside="name", show_n="column")                                         # n in a column on the right
  • likert(): diverging bars for rating scales, the levels in a few named bins (a ten-point scale reads 1–2, 3–5 | 6–8, 9–10), a middle level centred on the split, negatively worded items recoded and marked, sections as blocks, median, IQR and n beside each row, the binned key in the legend row.
  • spread(section=, panel_letters=, mean=, sort="median"): rows in lettered blocks, the mean as an open diamond beside the median dot, rows ordered by median.
  • bars(respondents=) counts each respondent once per answer, as a share of the panel's respondents, and says that several answers were possible; context= draws an answer outside the ranking in grey; header="n" gives each facet its n; show_n="column" writes each bar's n right of it; inside="name" names each stacked segment inside it, so rows may hold different answers.

Options every chart shares

The same question gets the same option in every chart that has the concept: order, sort, colors, highlight, key_title, x_title, y_title, reference, percent, show_n, min_n, clip and facet. reference={"Target": 0.9} draws labelled dashed lines on the value axis, highlight=["Unit B"] greys the other groups, facet="site" draws a panel per site on bars, scatter, raincloud and ridgeline (a block of rows on spread, dot plot and Likert). The options guide shows which chart has which.

Colours

Groups take a palette's colours in order, so two groups always get the same two colours and a group keeps its colour in every chart. hl.palettes() lists the six palettes, the purpose sets (two groups, greyscale print, risk of bias) and the ramps for amounts; hl.swatches() draws them; hl.use(palette="calm") changes the default; hl.use(colors={"Unit B": "#e79d01"}) pins a colour to a name; colors="blues" on a chart gives ordered groups the steps of one ramp; hl.colormap("blues") gives a ramp to your own matplotlib plots. help(hairline.palettes) has the details.

Files

save() writes PDF (fonts embedded), PNG and TIFF (600 dpi by default), SVG (text kept as text) and self-contained interactive HTML with tooltips. Files carry the figure's alt text as their description: its title, subtitle and what the data shows, in the figure's locale ("Bar chart. Highest: Ward (30); lowest: ICU (12)."). Every chart but the palette swatches describes its data this way; set figure.description to write your own. No timestamps: the same figure gives the same bytes again.

Design

  • hl.use(brand="_brand.yml") applies an institution's colours, fonts and sizes from a brand.yml file; several files layer from institution to document.
  • hl.use(colors={"Unit B": "#e79d01"}) pins a colour to a name across every chart.
  • Palettes are checked for colour-vision separation and contrast; hl.check_palette() reports the numbers.
  • hl.use(scheme="dark", accent="#0b6e4f") draws on a dark surface with an accent for single series.

More figures, Python and R side by side, and the colour guide: https://github.com/schradern/hairline.

The same figure in Python and R

Author

Nikolas Schrader (hi@nikolasschrader.com), ORCID 0009-0001-4616-3804.

How to cite

If hairline helped you make the figures in your work, please cite it; hl.citation() gives the reference and hl.citation("bibtex") this entry:

@Manual{schrader2026hairline,
  title = {hairline: Clean, Predictable Figures for Medical and Data Science},
  author = {Nikolas Schrader},
  year = {2026},
  note = {Python package version 0.4.0},
  doi = {10.5281/zenodo.23456211},
}

Licence

MIT. The bundled Hairline Sans font is a modified Public Sans (SIL Open Font License 1.1).

Metadata

Release files for hairline 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for hairline 0.4.0
File Size Uploaded Provenance Actions
hairline-0.4.0.tar.gz 1.1 MB Without provenance Details for hairline-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for hairline 0.4.0
File Interpreter ABI Platform Actions
hairline-0.4.0-py3-none-any.whl Python 3 none any Details for hairline-0.4.0-py3-none-any.whl

Total release size: 1.6 MB

Release files / hairline-0.4.0.tar.gz

Download URL hairline-0.4.0.tar.gz
Size 1.1 MB
Tags Source
SHA-256 checksum
How to use checksums
b56fdf8182917138fde155d75dafbb9a82922aa8600997a0fc7e1457ab1db4d8
BLAKE2b-256 checksum
How to use checksums
dfd924bbfdacda803a3525ad0b75513df5c17f6b6a6249bbeb0373188a36a932
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / hairline-0.4.0-py3-none-any.whl

Download URL hairline-0.4.0-py3-none-any.whl
Size 578.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
684a31f9ed95c4ad4fbff2195abdf04860c574680a7eaab9d5d900d435d3e610
BLAKE2b-256 checksum
How to use checksums
19a212b1dd6b2d8d2b91703e1359c436759b3d17d8acc3d7d80d244aeac48cd7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.5 {"installer":{"name":"uv","version":"0.13.5","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for hairline 0.4.0

Provenance

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page