Metadata-Version: 2.4
Name: workforce-plotting
Version: 0.5.0
Summary: Simple plotnine figures with Opportunity Insights styling.
Author: Corey Gelb-Bicknell
License-Expression: MIT
Project-URL: Repository, https://github.com/coreygb1/workforce-plotting
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: plotnine<0.16,>=0.15
Requires-Dist: pandas>=2.2
Requires-Dist: oi-tools>=0.11.7
Provides-Extra: polars
Requires-Dist: polars>=1; extra == "polars"
Requires-Dist: pyarrow>=14; extra == "polars"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Requires-Dist: polars>=1; extra == "dev"
Requires-Dist: pyarrow>=14; extra == "dev"
Dynamic: license-file

# 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:

```bash
uv add 'workforce-plotting[polars]'
```

Or use pip:

```bash
pip install 'workforce-plotting[polars]'
```

For local development from this checkout:

```bash
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.

```python
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.

```python
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:

```python
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.

```python
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:

```python
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:

```python
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`.

```python
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.

```bash
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.

```bash
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.
