Skip to main content

workforce-plotting

Six small plotnine functions with a shared paper style based on Opportunity Insights. Supply prepared estimates and confidence bounds; the functions only draw them. Every function returns a plotnine.ggplot that you can edit with ordinary layers.

Install

Python 3.12 or newer is required (matching oi-tools). For a Polars workflow:

uv add 'workforce-plotting[polars]'

Or use pip:

pip install 'workforce-plotting[polars]'

For local development from this checkout:

pip install -e '.[dev]'

For Polars input, install the polars extra, which also supplies the Arrow conversion dependency. Pandas input needs no extra.

Getting help

Function help describes the arguments and shows a short example.

from workforce_plotting import plot_lines
help(plot_lines)

In Jupyter, use plot_lines? or press Shift+Tab inside the parentheses. Column arguments such as x, y, and series are names in your dataframe, not arrays. series="city" means one color and legend entry per city; plot_lines also connects observations separately within each city. Estimates and confidence bounds must already be calculated. Every plot function returns an editable plotnine plot, with no automatic saving.

Functions

Function Use
plot_lines(data, x=..., y=..., series=...) Event studies, trajectories, model complexity
plot_validation(data, x=..., y=...) RCT versus digital-twin estimates with an identity line
plot_bars(data, x=..., y=..., series=...) Already-calculated values by category
plot_scatter(data, x=..., y=..., fitted=...) Unconnected points, optional CIs and a supplied fitted curve
plot_intervals(data, x=..., y=..., lower=..., upper=...) Estimates and supplied confidence intervals
plot_heatmap(data, x=..., y=..., fill=...) Numeric cells with optional row and column groups
theme_workforce() Times New Roman, gray axes, white background, no grid

plot_lines accepts lower and upper columns and points=False. plot_scatter also accepts lower and upper for supplied confidence bounds. Its points remain unconnected even when a separate fitted curve is supplied. plot_validation accepts x_lower, x_upper, y_lower, y_upper, gaps="horizontal" or "vertical", and a common (min, max) pair of limits. Use plot_validation(df, x="dml", y="rct", series="program_name") to color the estimates, intervals, and gap lines by program. The identity line has slope one in data units; the panel follows the figure's aspect ratio. The five non-heatmap functions accept series for discrete groups. Use ordered categorical columns to control color/legend order. Colors are teal, orange, navy, purple, blue, red, and dark green from the public oi_tools.figures.OIColors API. For a different mapping, add a plotnine manual color or fill scale.

import plotnine as pn
from workforce_plotting import plot_lines

p = plot_lines(df, x="year", y="earnings", series="group")
p += pn.labs(x="Years since enrollment", y="Mean annual earnings")
p.save("earnings.svg")

Dataframes should be tidy: one row per plotted point, with separate columns for x, y, and an optional series. Lines connect points in x order within each series. Include a row with a missing y where a line should break; simply omitting a row connects the remaining observations. Fitted lines use the same column names as the scatter data. No smoothing, RMSE calculation, confidence-interval estimation, or automatic saving happens inside the plotting functions.

Add pn.coord_flip() for horizontal bars/intervals; use ordinary plotnine scales for dollars, percentages, limits, or log axes. The default font is Times New Roman when installed. The theme checks for DejaVu Serif, DejaVu Sans, STIXGeneral, and other available families before rendering. An empty font list triggers registration of the bundled DejaVu Serif. Override fonts, dimensions, or text size with theme_workforce(base_family=..., base_size=..., width=..., height=...). For example, base_family="DejaVu Sans" selects sans-serif type. Use title= for a plot title. Add logos, notes, and paper-specific annotations with plotnine.

Paper defaults

  • Times New Roman when available, 12-point text, 1.2 line spacing, and an 8-by-5-inch canvas (heatmaps use a wider slide layout).
  • Gray 0.54-point axes/ticks, 10-point axis-title padding in both directions, 2% outer margins, 4.14-point ticks, no grid, and an inside upper-left vertical legend with a transparent background.
  • Dots use plotnine size 3.75. Legend dots are 25% larger; connected-line plots show dots in the legend when points are enabled and lines otherwise.
  • Confidence intervals use a 0.54-point stroke. Dots and interval strokes are separate layers, so changing one does not change the other.

All six functions accept title= for a centered plot title. Grouped bars, validation plots, and intervals on categorical axes put the legend above the panel. For longer category names, supply labels with line breaks or use scale_x_discrete(labels=...) to wrap them. Datetime x-axes covering less than a day show clock times in the data's time zone.

Point-based functions accept point_size. Those with intervals also accept ci_width (stroke width in points) and cap_width (plot-axis units perpendicular to the interval). Caps default to 1% of the numeric axis span or 0.12 category units on a categorical axis. A single numeric x position has no default caps. On a log axis, the cap width uses the transformed axis units. Set cap_width=0 to omit caps. Grouped plot_intervals narrows the default caps when x positions are closely spaced.

Dollar formatting is optional, rather than imposed on every outcome:

from workforce_plotting import dollars

p += pn.scale_y_continuous(labels=dollars)  # -$1K, $0, $2.5K, ...

plot_validation keeps its existing name and rectangular shape. Both axes share numeric limits, but equal physical scaling is not imposed.

Heatmap recipe

Supply one row per cell, with a numeric value and optional row and column groups. For example, a subgroup-bias table may contain program, site, dimension, subgroup, and bias (actual minus predicted earnings, in dollars). Sites may repeat across programs, and subgroup labels may repeat across dimensions. Duplicate cells within the same groups raise an error.

import plotnine as pn
from workforce_plotting import plot_heatmap

p = plot_heatmap(df, x="site", y="subgroup", fill="bias",
                 column_group="program", row_group="dimension",
                 lower="lower", upper="upper",
                 dollar_labels=True)
p += pn.labs(fill="Actual − predicted")
p.save("subgroup_bias.pdf")

The default canvas is landscape (11.8 by 5.2 inches), with angled column labels, bold program/group headings above columns, whitespace between row groups, proportional group widths/heights, and a shared horizontal red–white–blue colorbar centered at zero. Categories follow first appearance or their supplied categorical order, shared across groups; rows read top to bottom. Numeric axis labels are treated as equally spaced categories. Explicit missing values are gray; absent cells are blank. Use limits=(-7000, 7000) for a common scale across figures, covering all values. Without limits, the symmetric range is chosen automatically. Set show_values=True for smaller tables (with automatic text contrast and three-significant-digit labels; tile colors use the full values). dollar_labels=True formats both the colorbar and optional cell values; otherwise labels use the supplied numeric units. Use pn.labs() to set titles and labels and ordinary plotnine layers for exceptional adjustments.

The optional lower and upper columns must contain pointwise two-sided 95% confidence intervals. An outlined dot marks cells whose interval excludes zero (p < 0.05); missing estimates or incomplete intervals are not marked. The function draws supplied intervals as significance markers only and does not calculate uncertainty or adjust for multiple testing. Cell values and significance dots can be shown together. Row-group headings are hidden by default; use descriptive subgroup labels or restore headings with pn.theme(strip_text_y=pn.element_text(rotation=0, weight="bold")).

Titles remain ordinary plotnine labels. Move the legend without changing the plot constructor or shared theme:

p += pn.labs(title="Earnings Before and After Enrollment")
p += pn.theme(legend_position="inside", legend_position_inside=(0.97, 0.97),
              legend_justification_inside=(1, 1))  # upper-right

To put it below the figure, use pn.theme(legend_position="bottom", legend_direction="horizontal").

Event-study recipe

Use plot_lines with supplied estimates and confidence bounds, then add the reference lines explicitly. Here treatment begins at event year zero; a zero-effect line is added, but no treatment-timing line is imposed:

p = (
    plot_lines(df, x="event_year", y="effect", lower="lower", upper="upper")
    + pn.geom_hline(yintercept=0, color="#A0A0A0", size=0.54)
    + pn.scale_y_continuous(labels=dollars)
    + pn.labs(x="Years Relative to Treatment", y="Earnings Effect")
)

For unconnected cohort estimates plus a supplied curve, use plot_scatter(df, x="year", y="effect", lower="lower", upper="upper", fitted=curve). For estimates across categories, use plot_intervals. Pass fitted= to draw a curve from supplied values. For a single series, a supplied curve appears in teal with gray points in both plot_intervals and plot_scatter.

Styling your own plots

Use the theme and colors without using the plot constructors. WFColors is an alias of oi_tools.figures.OIColors, and theme_workforce builds on theme_oi. The oi-tools dependency remains; you only need workforce imports in your code. All plotting functions and styling live together in workforce_plotting/figures.py.

import polars as pl
import plotnine as pn
from workforce_plotting import theme_workforce, WFColors

df = pl.DataFrame({"year": [2020, 2021, 2022], "earnings": [20000, 23000, 25000]})
p = (
    pn.ggplot(df.to_pandas(), pn.aes(x="year", y="earnings"))
    + pn.geom_line(color=WFColors.TEAL)
    + pn.geom_point(color=WFColors.TEAL)
    + theme_workforce()
    + pn.labs(x="Year", y="Annual earnings")
)
p.save("earnings.svg")

Plot constructors accept Polars directly. When building a plotnine plot yourself, the explicit conversion above works with the supported plotnine version.

Default outputs

examples/default_examples.py draws all six functions with their basic calls: no added reference lines, titles, labels, scales, coordinates, or theme overrides. It uses the same data for scatter and validation so their default behavior can be compared directly. All values are invented.

python examples/default_examples.py outputs/defaults

Titles remain available through pn.labs(title=...); the plain default examples deliberately do not add them.

Editable examples

examples/paper_examples.py contains synthetic recipes for the paper/deck plot families. These are invented values, not research results.

python examples/paper_examples.py outputs/examples
pytest

Changes in 0.5

  • Added plot_heatmap for numeric cells with optional grouped rows and columns, a shared diverging color scale, optional values, and significance markers based on supplied confidence bounds.

Changes in 0.4

  • Validation plots accept series= to color by program or another grouping column.
  • Plot titles are larger and centered, confidence intervals have short caps by default, and interval plots accept a supplied fit.
  • Numeric group labels, sparse groups, missing estimates, and intraday axes render more reliably.

Changes in 0.3

  • Paper defaults: Times New Roman, inside vertical legends, five-point ticks, shared margins, and consistent axis-title spacing. Choose a different font explicitly with theme_workforce(base_family=...) for deck-style figures.
  • Consistent dots, larger legend dots, and independently sized intervals.
  • Optional scatter confidence intervals and an optional dollars labeler.
  • Complete function help plus plain-default and customized example scripts.

The five plot names and the rectangular validation layout are unchanged.

Changes from 0.1

This is a fresh API. The old Matplotlib functions, plotting dataclasses, curve fitting machinery, and aipw_analysis compatibility package have been removed. Plot creation and saving are now separate. The public API consists of the five plot functions, theme_workforce, WFColors, and the optional dollars formatter.

Metadata

Release files for workforce-plotting 0.5.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 workforce-plotting 0.5.0
File Size Uploaded Provenance Actions
workforce_plotting-0.5.0.tar.gz 26.6 kB With provenance Details for workforce_plotting-0.5.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for workforce-plotting 0.5.0
File Interpreter ABI Platform Actions
workforce_plotting-0.5.0-py3-none-any.whl Python 3 none any Details for workforce_plotting-0.5.0-py3-none-any.whl

Total release size: 40.9 kB

Release files / workforce_plotting-0.5.0.tar.gz

Download URL workforce_plotting-0.5.0.tar.gz
Size 26.6 kB
Tags Source
SHA-256 checksum
How to use checksums
4a23fada1b4ef9f3fe8fd7f9900f52bbca5bf037086172f4d721d0644f20d17c
BLAKE2b-256 checksum
How to use checksums
7d68a5e55ddfeb7075b1f660035f34ae999b978e27f3bf03f1a6738f393c9f6a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Release files / workforce_plotting-0.5.0-py3-none-any.whl

Download URL workforce_plotting-0.5.0-py3-none-any.whl
Size 14.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
9e07701e8052856f73b156496cf3b233f2ac03160d67f0ab8e11adc13f8fc59d
BLAKE2b-256 checksum
How to use checksums
19017304b0bc9a0a882ecae581094aa5be83dba4de052892187f425c20a1049a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

Security for workforce-plotting 0.5.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.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for workforce_plotting-0.5.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.

Transparency log

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