workforce-plotting 0.2.0__py3-none-any.whl → 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
1
  """Plotnine figures and styling for workforce research."""
2
2
 
3
3
  from .figures import (
4
- WFColors, plot_bars, plot_intervals, plot_lines, plot_scatter,
4
+ WFColors, dollars, plot_bars, plot_intervals, plot_lines, plot_scatter,
5
5
  plot_validation, theme_workforce,
6
6
  )
7
7
 
8
8
  __all__ = ["plot_lines", "plot_validation", "plot_bars", "plot_scatter",
9
- "plot_intervals", "theme_workforce", "WFColors"]
9
+ "plot_intervals", "theme_workforce", "WFColors", "dollars"]
@@ -1,41 +1,84 @@
1
- """Workforce plots, shared styling, and the Opportunity Insights color palette."""
1
+ """Workforce plots, shared paper styling, and the Opportunity Insights palette."""
2
2
 
3
+ from math import pi, sqrt
4
+ from pathlib import Path
5
+
6
+ import numpy as np
3
7
  import pandas as pd
4
8
  import plotnine as pn
5
- from matplotlib import font_manager
9
+ from matplotlib import font_manager, get_data_path
10
+ from mizani.labels import label_date
11
+ from mizani.palettes import hue_pal
6
12
  from oi_tools.figures import OIColors as WFColors, theme_oi
7
13
 
8
14
  PALETTE = [WFColors.TEAL, WFColors.ORANGE, WFColors.NAVY, WFColors.PURPLE,
9
15
  WFColors.BLUE, WFColors.RED, WFColors.DARK_GREEN]
10
16
 
11
17
 
12
- def theme_workforce(base_size=12, base_family=None, width=8, height=5):
13
- """White background, gray axes, no grid, and a bottom legend.
18
+ def theme_workforce(base_size=12, base_family="Times New Roman", width=8, height=5):
19
+ """Apply the paper style to a plotnine plot.
20
+
21
+ base_size: Base text size in points (12).
22
+ base_family: Font family (Times New Roman). The theme silently selects
23
+ an available fallback when the preferred paper fonts are missing.
24
+ width, height: Figure size in inches (8 by 5).
14
25
 
15
- Dimensions are in inches. Install Lucida Sans to match the reference deck.
16
- If unavailable, Matplotlib falls back to its default sans-serif font.
26
+ Example
27
+ -------
28
+ >>> p = p + theme_workforce(width=10, height=6)
17
29
  """
18
- if base_family is None:
19
- base_family = ("Lucida Sans" if "Lucida Sans" in font_manager.get_font_names()
20
- else "DejaVu Sans")
30
+ fallback_families = ("DejaVu Serif", "DejaVu Sans", "STIXGeneral")
31
+ if base_family == "Times New Roman" or base_family in fallback_families:
32
+ available = set(font_manager.get_font_names())
33
+ if base_family not in available:
34
+ if not available:
35
+ bundled = Path(get_data_path()) / "fonts" / "ttf"
36
+ for path in bundled.glob("DejaVuSerif*.ttf"):
37
+ font_manager.fontManager.addfont(path)
38
+ available = set(font_manager.get_font_names())
39
+ if not available:
40
+ raise RuntimeError("Matplotlib requires a font to render plot text.")
41
+ base_family = next(
42
+ (family for family in fallback_families if family in available),
43
+ min(available),
44
+ )
21
45
  return theme_oi(base_size, base_family, width, height) + pn.theme(
46
+ text=pn.element_text(linespacing=1.2),
22
47
  axis_line=pn.element_line(color="#A0A0A0", size=0.54),
23
48
  axis_ticks=pn.element_line(color="#A0A0A0", size=0.54),
49
+ axis_ticks_length=4.14,
24
50
  axis_text=pn.element_text(color="black", size=base_size),
25
- axis_title=pn.element_text(size=base_size, lineheight=1.8),
26
- axis_title_y=pn.element_text(margin={"r": 16}),
27
- axis_title_x=pn.element_text(margin={"t": 14}),
51
+ axis_title=pn.element_text(size=base_size),
52
+ axis_title_y=pn.element_text(margin={"r": 10}),
53
+ axis_title_x=pn.element_text(margin={"t": 10}),
54
+ plot_title=pn.element_text(size=base_size + 2, ha="center", margin={"b": 8}),
55
+ plot_title_position="plot",
56
+ legend_position="inside",
57
+ legend_position_inside=(0.03, 0.97),
58
+ legend_justification_inside=(0, 1),
59
+ legend_direction="vertical",
60
+ legend_background=pn.element_blank(),
28
61
  legend_text=pn.element_text(size=base_size),
29
62
  legend_title=pn.element_blank(),
30
- plot_margin_top=0.044,
31
- plot_margin_right=0.015,
32
- plot_margin_bottom=0.025,
63
+ plot_margin=0.02,
33
64
  panel_grid=pn.element_blank(),
34
65
  axis_ticks_minor=pn.element_blank(),
35
66
  legend_key=pn.element_blank(),
36
67
  )
37
68
 
38
69
 
70
+ def dollars(values):
71
+ """Format tick values in dollars as $1K, $2.5K, and $0.
72
+
73
+ values: Dollar amounts supplied by the axis scale.
74
+
75
+ Example
76
+ -------
77
+ >>> p = p + pn.scale_y_continuous(labels=dollars)
78
+ """
79
+ return [f"{'-' if v < 0 else ''}${abs(v) / 1000:g}K" if v else "$0" for v in values]
80
+
81
+
39
82
  def _data(data):
40
83
  """Keep pandas inputs; convert Polars using its public conversion method."""
41
84
  if isinstance(data, pd.DataFrame):
@@ -48,111 +91,304 @@ def _interval(lower, upper):
48
91
  raise ValueError("Supply both lower and upper interval columns, or neither.")
49
92
 
50
93
 
51
- def plot_lines(data, *, x, y, series=None, lower=None, upper=None, points=True):
52
- """Lines with optional points and supplied confidence intervals.
94
+ def _group_data(data, series):
95
+ data = _data(data)
96
+ if series is not None and not _categorical(data[series]):
97
+ return data.assign(**{series: data[series].astype("category")})
98
+ return data
99
+
100
+
101
+ def _group_colors(data, series, fitted=None):
102
+ groups = data[series] if fitted is None else pd.concat([data[series], fitted[series]])
103
+ count = groups.nunique()
104
+ return PALETTE if count <= len(PALETTE) else hue_pal()(count)
105
+
106
+
107
+ def _x_spacing(values):
108
+ spacing = values[np.isfinite(values)].drop_duplicates().sort_values().diff().min()
109
+ return spacing if pd.notna(spacing) else 1
110
+
111
+
112
+ class _IntervalDodge(pn.position_dodge):
113
+ def setup_params(self, data):
114
+ params = super().setup_params(data)
115
+ params["width"] = 0.5 * _x_spacing(data["x"])
116
+ return params
117
+
118
+
119
+ class _ErrorBar(pn.geom_errorbar):
120
+ DEFAULT_PARAMS = {**pn.geom_errorbar.DEFAULT_PARAMS, "width": None, "categorical": False}
121
+
122
+ def setup_data(self, data):
123
+ # Plotnine has already mapped discrete axes and transformed log axes.
124
+ width = self.params["width"]
125
+ if width is None:
126
+ x = data.loc[np.isfinite(data["x"]), "x"]
127
+ span = x.max() - x.min()
128
+ width = 0.01 * span if span > 0 else 0
129
+ if self.params["categorical"]:
130
+ width = 0.12
131
+ if isinstance(self.params["position"], _IntervalDodge):
132
+ width = min(width, 0.5 * _x_spacing(x))
133
+ data["width"] = width
134
+ return super().setup_data(data)
135
+
136
+
137
+ class _Bar(pn.geom_col):
138
+ def setup_data(self, data):
139
+ data["width"] = self.params["width"] * _x_spacing(data["x"])
140
+ return super().setup_data(data)
53
141
 
54
- Use an ordered categorical series to control legend/color order. Add scales,
55
- reference lines, facets, and labels using ordinary plotnine layers.
142
+
143
+ def _categorical(values):
144
+ return not (pd.api.types.is_numeric_dtype(values)
145
+ or pd.api.types.is_datetime64_any_dtype(values))
146
+
147
+
148
+ def _time_axis(plot, values):
149
+ if not pd.api.types.is_datetime64_any_dtype(values):
150
+ return plot
151
+ start, end = values.min(), values.max()
152
+ span = end - start
153
+ if not pd.Timedelta(0) < span < pd.Timedelta(days=1):
154
+ return plot
155
+ fmt = "%H:%M:%S" if span < pd.Timedelta(minutes=5) else "%H:%M"
156
+ if start.date() != end.date():
157
+ fmt = "%m-%d " + fmt
158
+ return plot + pn.scale_x_datetime(labels=label_date(fmt, tz=values.dt.tz))
159
+
160
+
161
+ def plot_lines(data, *, x, y, series=None, lower=None, upper=None, points=True,
162
+ point_size=3.75, ci_width=0.54, cap_width=None, title=None):
163
+ """Connect points in x order within each series.
164
+
165
+ data: Pandas or Polars dataframe with one row per point.
166
+ x, y: Column names for the horizontal positions and values.
167
+ series: Optional group column for separate lines and colors.
168
+ lower, upper: Optional pair of y interval-bound columns.
169
+ points: Draw dots (True).
170
+ point_size: Dot size in plotnine units (3.75).
171
+ ci_width: Interval stroke width in points (0.54).
172
+ cap_width: Cap width in plot-axis units. Defaults to short caps. Use 0 for none.
173
+ title: Optional plot title.
174
+
175
+ Example
176
+ -------
177
+ >>> plot_lines(df, x="year", y="effect", series="group")
56
178
  """
57
179
  _interval(lower, upper)
58
180
  mapping = pn.aes(x=x, y=y, group=1)
59
181
  if series is not None:
60
182
  mapping.update(color=series, group=series)
61
- p = pn.ggplot(_data(data), mapping)
183
+ data = _group_data(data, series)
184
+ p = pn.ggplot(data, mapping)
62
185
  if lower is not None:
63
- p += pn.geom_errorbar(pn.aes(ymin=lower, ymax=upper), width=0.08,
64
- size=0.4, **({} if series else {"color": WFColors.TEAL}))
65
- p += pn.geom_line(size=0.914, **({} if series else {"color": WFColors.TEAL}))
186
+ p += _ErrorBar(pn.aes(ymin=lower, ymax=upper), width=cap_width,
187
+ categorical=_categorical(data[x]), na_rm=True,
188
+ size=ci_width / sqrt(pi), show_legend=False,
189
+ **({} if series is not None else {"color": WFColors.TEAL}))
190
+ p += pn.geom_line(size=0.914, show_legend=not points,
191
+ **({} if series is not None else {"color": WFColors.TEAL}))
66
192
  if points:
67
- p += pn.geom_point(size=3.45, stroke=0, **({} if series else {"color": WFColors.TEAL}))
193
+ p += pn.geom_point(size=point_size, stroke=0, na_rm=True,
194
+ **({} if series is not None else {"color": WFColors.TEAL}))
68
195
  if series is not None:
69
- p += pn.scale_color_manual(values=PALETTE)
70
- return p + theme_workforce()
196
+ p += pn.scale_color_manual(values=_group_colors(data, series))
197
+ if points:
198
+ p += pn.guides(color=pn.guide_legend(override_aes={"size": point_size * 1.25}))
199
+ return _time_axis(p + theme_workforce() + pn.labs(title=title), data[x])
71
200
 
72
201
 
73
202
  def plot_validation(data, *, x, y, x_lower=None, x_upper=None,
74
- y_lower=None, y_upper=None, gaps=None, limits=None):
75
- """Compare estimates against a 45-degree identity line.
203
+ y_lower=None, y_upper=None, series=None, gaps=None, limits=None,
204
+ point_size=3.75, ci_width=0.54, cap_width=None, title=None):
205
+ """Compare paired estimates against y=x using common axis limits.
76
206
 
77
- x/y confidence bounds are optional. ``gaps`` may be 'vertical' (from y to x)
78
- or 'horizontal' (from x to y). Both axes use the same numeric limits.
79
- Default limits include all supplied estimates and interval endpoints.
207
+ data: Pandas or Polars dataframe with one row per pair.
208
+ x, y: Column names for the two estimates.
209
+ x_lower, x_upper: Optional pair of horizontal interval-bound columns.
210
+ y_lower, y_upper: Optional pair of vertical interval-bound columns.
211
+ series: Optional group column for coloring estimates and intervals.
212
+ gaps: Optional "horizontal" or "vertical" segments to the identity line.
213
+ limits: Common (min, max) range. Defaults to the estimates and bounds.
214
+ point_size: Dot size in plotnine units (3.75).
215
+ ci_width: Interval stroke width in points (0.54).
216
+ cap_width: Cap width in axis units (1% of the shared range). Use 0 for none.
217
+ title: Optional plot title.
218
+
219
+ Example
220
+ -------
221
+ >>> plot_validation(df, x="dml_effect", y="rct_effect")
80
222
  """
81
223
  _interval(x_lower, x_upper)
82
224
  _interval(y_lower, y_upper)
83
225
  if gaps not in (None, "vertical", "horizontal"):
84
226
  raise ValueError("gaps must be None, 'vertical', or 'horizontal'.")
85
- data = _data(data)
86
- if limits is None:
227
+ data = _group_data(data, series)
228
+ pairs = data[[x, y]].to_numpy(dtype=float, na_value=np.nan)
229
+ data = data.loc[np.isfinite(pairs).all(axis=1)]
230
+ expand = limits is None
231
+ if expand:
87
232
  columns = [v for v in (x, y, x_lower, x_upper, y_lower, y_upper)
88
233
  if v is not None]
89
- values = pd.concat([data[v] for v in columns]).dropna()
90
- if values.empty:
91
- raise ValueError("Supply at least one nonmissing estimate or explicit limits.")
234
+ values = pd.concat([data[v] for v in columns]).to_numpy(dtype=float, na_value=np.nan)
235
+ values = values[np.isfinite(values)]
236
+ if not values.size:
237
+ raise ValueError("Supply at least one finite pair of estimates or explicit limits.")
92
238
  limits = (values.min(), values.max())
93
- p = pn.ggplot(data, pn.aes(x=x, y=y)) + pn.geom_abline(
239
+ if cap_width is None:
240
+ cap_width = 0.01 * (limits[1] - limits[0])
241
+ mapping = pn.aes(x=x, y=y)
242
+ if series is not None:
243
+ mapping.update(color=series)
244
+ point_color = {} if series is not None else {"color": WFColors.TEAL}
245
+ gap_color = {} if series is not None else {"color": WFColors.ORANGE}
246
+ p = pn.ggplot(data, mapping) + pn.geom_abline(
94
247
  intercept=0, slope=1, color="black", size=0.6)
95
248
  if gaps == "vertical":
96
- p += pn.geom_segment(pn.aes(xend=x, yend=x), color=WFColors.ORANGE, size=0.5, alpha=0.8)
249
+ p += pn.geom_segment(pn.aes(xend=x, yend=x), size=0.5, alpha=0.8,
250
+ show_legend=False, **gap_color)
97
251
  elif gaps == "horizontal":
98
- p += pn.geom_segment(pn.aes(xend=y, yend=y), color=WFColors.ORANGE, size=0.5, alpha=0.8)
252
+ p += pn.geom_segment(pn.aes(xend=y, yend=y), size=0.5, alpha=0.8,
253
+ show_legend=False, **gap_color)
99
254
  if x_lower is not None:
100
- p += pn.geom_errorbarh(pn.aes(xmin=x_lower, xmax=x_upper), height=0,
101
- color=WFColors.TEAL, size=0.5, alpha=0.5)
255
+ p += pn.geom_errorbarh(pn.aes(xmin=x_lower, xmax=x_upper, height=cap_width),
256
+ size=ci_width / sqrt(pi), alpha=0.5, na_rm=True,
257
+ show_legend=False, **point_color)
102
258
  if y_lower is not None:
103
- p += pn.geom_errorbar(pn.aes(ymin=y_lower, ymax=y_upper), width=0,
104
- color=WFColors.TEAL, size=0.5, alpha=0.5)
105
- return (p + pn.geom_point(color=WFColors.TEAL, size=3.45, stroke=0)
106
- + pn.coord_cartesian(xlim=limits, ylim=limits) + theme_workforce())
259
+ p += pn.geom_errorbar(pn.aes(ymin=y_lower, ymax=y_upper, width=cap_width),
260
+ size=ci_width / sqrt(pi), alpha=0.5, na_rm=True,
261
+ show_legend=False, **point_color)
262
+ p += pn.geom_point(size=point_size, stroke=0, **point_color)
263
+ p = (p + pn.coord_cartesian(xlim=limits, ylim=limits, expand=expand)
264
+ + theme_workforce() + pn.labs(title=title))
265
+ if series is not None:
266
+ p = (p + pn.scale_color_manual(values=_group_colors(data, series),
267
+ labels=lambda values: [
268
+ "Missing" if pd.isna(value) else str(value)
269
+ for value in values
270
+ ])
271
+ + pn.guides(color=pn.guide_legend(ncol=2, byrow=True,
272
+ override_aes={"size": point_size * 1.25}))
273
+ + pn.theme(legend_position="top", legend_direction="horizontal"))
274
+ return p
275
+
107
276
 
277
+ def plot_bars(data, *, x, y, series=None, title=None):
278
+ """Draw bars from values you supply.
108
279
 
109
- def plot_bars(data, *, x, y, series=None):
110
- """Bars for already-calculated values; optional series are side by side.
280
+ data: Pandas or Polars dataframe with one row per bar.
281
+ x: Category column. Use ordered categories to set the display order.
282
+ y: Numeric bar-height column.
283
+ series: Optional group column for side-by-side bars and colors.
284
+ title: Optional plot title.
111
285
 
112
- Set x to an ordered categorical column, or add scale_x_discrete(limits=...),
113
- to choose the category order. Add coord_flip() for horizontal bars.
286
+ Example
287
+ -------
288
+ >>> plot_bars(df, x="specification", y="rmse")
114
289
  """
115
290
  mapping = pn.aes(x=x, y=y, group=1)
116
291
  if series is not None:
117
292
  mapping.update(fill=series, group=series)
118
- p = pn.ggplot(_data(data), mapping) + pn.geom_col(
119
- width=0.7, position="dodge", **({} if series else {"fill": WFColors.TEAL}))
293
+ data = _group_data(data, series)
294
+ position = "identity" if series is None else pn.position_dodge2(preserve="single", padding=0)
295
+ p = pn.ggplot(data, mapping) + _Bar(
296
+ width=0.7 if series is not None else 0.55, position=position,
297
+ **({} if series is not None else {"fill": WFColors.TEAL}))
298
+ p = p + theme_workforce() + pn.labs(title=title)
120
299
  if series is not None:
121
- p += pn.scale_fill_manual(values=PALETTE)
122
- return p + theme_workforce()
300
+ p = (p + pn.scale_fill_manual(values=_group_colors(data, series))
301
+ + pn.guides(fill=pn.guide_legend(ncol=2, byrow=True))
302
+ + pn.theme(legend_position="top", legend_direction="horizontal"))
303
+ return _time_axis(p, data[x])
123
304
 
124
305
 
125
- def plot_scatter(data, *, x, y, series=None, fitted=None):
126
- """Points, optionally with a separate dataframe of precomputed fitted values.
306
+ def plot_scatter(data, *, x, y, series=None, fitted=None, lower=None, upper=None,
307
+ point_size=3.75, ci_width=0.54, cap_width=None, title=None):
308
+ """Draw unconnected points with optional intervals and a supplied curve.
127
309
 
128
- ``fitted`` uses the same x, y, and (when specified) series column names.
129
- The function never fits or smooths a curve.
310
+ data: Pandas or Polars dataframe with one row per point.
311
+ x, y: Column names for the two plotted variables.
312
+ series: Optional group column for separate colors.
313
+ fitted: Optional dataframe of fitted values using the same x, y,
314
+ and series column names. The supplied values are joined in x order.
315
+ lower, upper: Optional pair of y interval-bound columns.
316
+ point_size: Dot size in plotnine units (3.75).
317
+ ci_width: Interval stroke width in points (0.54).
318
+ cap_width: Cap width in plot-axis units. Defaults to short caps. Use 0 for none.
319
+ title: Optional plot title.
320
+
321
+ Example
322
+ -------
323
+ >>> plot_scatter(df, x="year", y="effect", fitted=curve_df)
130
324
  """
325
+ _interval(lower, upper)
131
326
  mapping = pn.aes(x=x, y=y, group=1)
132
327
  if series is not None:
133
328
  mapping.update(color=series, group=series)
134
- p = pn.ggplot(_data(data), mapping)
329
+ data = _group_data(data, series)
330
+ fitted = None if fitted is None else _group_data(fitted, series)
331
+ p = pn.ggplot(data, mapping)
332
+ point_color = "#808080" if fitted is not None else WFColors.TEAL
333
+ if lower is not None:
334
+ p += _ErrorBar(pn.aes(ymin=lower, ymax=upper), width=cap_width,
335
+ categorical=_categorical(data[x]), na_rm=True,
336
+ size=ci_width / sqrt(pi), show_legend=False,
337
+ **({} if series is not None else {"color": point_color}))
135
338
  if fitted is not None:
136
- p += pn.geom_line(data=_data(fitted), size=0.914,
137
- **({} if series else {"color": WFColors.NAVY}))
138
- p += pn.geom_point(size=3.45, stroke=0, **({} if series else {"color": WFColors.TEAL}))
339
+ p += pn.geom_line(data=fitted, size=0.914, show_legend=False,
340
+ **({} if series is not None else {"color": WFColors.TEAL}))
341
+ p += pn.geom_point(size=point_size, stroke=0, na_rm=True,
342
+ **({} if series is not None else {"color": point_color}))
139
343
  if series is not None:
140
- p += pn.scale_color_manual(values=PALETTE)
141
- return p + theme_workforce()
344
+ p += pn.scale_color_manual(values=_group_colors(data, series, fitted))
345
+ p += pn.guides(color=pn.guide_legend(override_aes={"size": point_size * 1.25}))
346
+ return _time_axis(p + theme_workforce() + pn.labs(title=title), data[x])
347
+
142
348
 
349
+ def plot_intervals(data, *, x, y, lower, upper, series=None, fitted=None,
350
+ point_size=3.75, ci_width=0.54, cap_width=None, title=None):
351
+ """Draw estimates and their supplied intervals across categories.
143
352
 
144
- def plot_intervals(data, *, x, y, lower, upper, series=None):
145
- """Points with supplied interval bounds, dodged when series are supplied.
353
+ data: Pandas or Polars dataframe with one row per estimate.
354
+ x, y: Category and estimate column names.
355
+ lower, upper: Required columns containing the interval endpoints.
356
+ series: Optional group column for side-by-side estimates and colors.
357
+ fitted: Optional dataframe of fitted values with the same x, y, and series columns.
358
+ point_size: Dot size in plotnine units (3.75).
359
+ ci_width: Interval stroke width in points (0.54).
360
+ cap_width: Cap width in plot-axis units. Defaults to short caps. Use 0 for none.
361
+ title: Optional plot title.
146
362
 
147
- x is the category and y the estimate. Add coord_flip() for a horizontal
148
- coefficient plot. Interval bounds are used as supplied, without adjustment.
363
+ Example
364
+ -------
365
+ >>> plot_intervals(df, x="program", y="effect", lower="lo", upper="hi")
149
366
  """
150
- mapping = pn.aes(x=x, y=y, ymin=lower, ymax=upper)
367
+ mapping = pn.aes(x=x, y=y, group=1)
151
368
  if series is not None:
152
369
  mapping.update(color=series, group=series)
153
- p = pn.ggplot(_data(data), mapping) + pn.geom_pointrange(
154
- position=pn.position_dodge(width=0.5), size=0.5,
155
- **({} if series else {"color": WFColors.TEAL}))
370
+ data = _group_data(data, series)
371
+ fitted = None if fitted is None else _group_data(fitted, series)
372
+ point_color = "#808080" if fitted is not None else WFColors.TEAL
373
+ colors = {} if series is not None else {"color": point_color}
374
+ categorical = _categorical(data[x])
375
+ p = pn.ggplot(data, mapping)
376
+ if fitted is not None:
377
+ p += pn.geom_line(data=fitted, size=0.914, show_legend=False,
378
+ **({} if series is not None else {"color": WFColors.TEAL}))
379
+ position = "identity" if series is None else _IntervalDodge(width=0.5)
380
+ p = (p + _ErrorBar(pn.aes(ymin=lower, ymax=upper), width=cap_width,
381
+ categorical=categorical, na_rm=True,
382
+ position=position, size=ci_width / sqrt(pi),
383
+ show_legend=False, **colors)
384
+ + pn.geom_point(position=position, size=point_size, stroke=0,
385
+ **colors))
156
386
  if series is not None:
157
- p += pn.scale_color_manual(values=PALETTE)
158
- return p + theme_workforce()
387
+ p += pn.scale_color_manual(values=_group_colors(data, series, fitted))
388
+ p += pn.guides(color=pn.guide_legend(ncol=2 if categorical else None,
389
+ byrow=categorical,
390
+ override_aes={"size": point_size * 1.25}))
391
+ p = p + theme_workforce() + pn.labs(title=title)
392
+ if series is not None and categorical:
393
+ p += pn.theme(legend_position="top", legend_direction="horizontal")
394
+ return _time_axis(p, data[x])
@@ -0,0 +1,263 @@
1
+ Metadata-Version: 2.4
2
+ Name: workforce-plotting
3
+ Version: 0.4.0
4
+ Summary: Simple plotnine figures with Opportunity Insights styling.
5
+ Author: Corey Gelb-Bicknell
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/coreygb1/workforce-plotting
8
+ Requires-Python: >=3.12
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: plotnine<0.16,>=0.15
12
+ Requires-Dist: pandas>=2.2
13
+ Requires-Dist: oi-tools>=0.11.7
14
+ Provides-Extra: polars
15
+ Requires-Dist: polars>=1; extra == "polars"
16
+ Requires-Dist: pyarrow>=14; extra == "polars"
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8; extra == "dev"
19
+ Requires-Dist: build; extra == "dev"
20
+ Requires-Dist: twine; extra == "dev"
21
+ Requires-Dist: polars>=1; extra == "dev"
22
+ Requires-Dist: pyarrow>=14; extra == "dev"
23
+ Dynamic: license-file
24
+
25
+ # workforce-plotting
26
+
27
+ Five small plotnine functions with a shared paper style based on Opportunity Insights. Supply
28
+ prepared estimates and confidence bounds; the functions only draw them. Every
29
+ function returns a `plotnine.ggplot` that you can edit with ordinary layers.
30
+
31
+ ## Install
32
+
33
+ Python 3.12 or newer is required (matching `oi-tools`). For a Polars workflow:
34
+
35
+ ```bash
36
+ uv add 'workforce-plotting[polars]'
37
+ ```
38
+
39
+ Or use pip:
40
+
41
+ ```bash
42
+ pip install 'workforce-plotting[polars]'
43
+ ```
44
+
45
+ For local development from this checkout:
46
+
47
+ ```bash
48
+ pip install -e '.[dev]'
49
+ ```
50
+
51
+ For Polars input, install the `polars` extra, which also supplies the Arrow
52
+ conversion dependency. Pandas input needs no extra.
53
+
54
+ ## Getting help
55
+
56
+ Function help describes the arguments and shows a short example.
57
+
58
+ ```python
59
+ from workforce_plotting import plot_lines
60
+ help(plot_lines)
61
+ ```
62
+
63
+ In Jupyter, use `plot_lines?` or press Shift+Tab inside the parentheses. Column
64
+ arguments such as `x`, `y`, and `series` are names in your dataframe, not arrays.
65
+ `series="city"` means one color and legend entry per city; `plot_lines` also
66
+ connects observations separately within each city. Estimates and confidence
67
+ bounds must already be calculated. Every plot function returns an editable
68
+ plotnine plot, with no automatic saving.
69
+
70
+ ## Functions
71
+
72
+ | Function | Use |
73
+ |---|---|
74
+ | `plot_lines(data, x=..., y=..., series=...)` | Event studies, trajectories, model complexity |
75
+ | `plot_validation(data, x=..., y=...)` | RCT versus digital-twin estimates with an identity line |
76
+ | `plot_bars(data, x=..., y=..., series=...)` | Already-calculated values by category |
77
+ | `plot_scatter(data, x=..., y=..., fitted=...)` | Unconnected points, optional CIs and a supplied fitted curve |
78
+ | `plot_intervals(data, x=..., y=..., lower=..., upper=...)` | Estimates and supplied confidence intervals |
79
+ | `theme_workforce()` | Times New Roman, gray axes, white background, no grid |
80
+
81
+ `plot_lines` accepts `lower` and `upper` columns and `points=False`.
82
+ `plot_scatter` also accepts `lower` and `upper` for supplied confidence bounds.
83
+ Its points remain unconnected even when a separate fitted curve is supplied.
84
+ `plot_validation` accepts `x_lower`, `x_upper`, `y_lower`, `y_upper`,
85
+ `gaps="horizontal"` or `"vertical"`, and a common `(min, max)` pair of `limits`.
86
+ Use `plot_validation(df, x="dml", y="rct", series="program_name")`
87
+ to color the estimates, intervals, and gap lines by program.
88
+ The identity line has slope one in data units; the panel follows the figure's
89
+ aspect ratio. All five functions accept `series` for discrete groups. Use ordered
90
+ categorical columns to control color/legend order. Colors are teal, orange, navy,
91
+ purple, blue, red, and dark green from the public `oi_tools.figures.OIColors` API.
92
+ For a different mapping, add a plotnine manual color or fill scale.
93
+
94
+ ```python
95
+ import plotnine as pn
96
+ from workforce_plotting import plot_lines
97
+
98
+ p = plot_lines(df, x="year", y="earnings", series="group")
99
+ p += pn.labs(x="Years since enrollment", y="Mean annual earnings")
100
+ p.save("earnings.svg")
101
+ ```
102
+
103
+ Dataframes should be tidy: one row per plotted point, with separate columns for
104
+ x, y, and an optional series. Lines connect points in x order within each series.
105
+ Include a row with a missing y where a line should break; simply omitting a row
106
+ connects the remaining observations. Fitted lines use the same column names as
107
+ the scatter data. No smoothing, RMSE calculation, confidence-interval estimation,
108
+ or automatic saving happens inside the plotting functions.
109
+
110
+ Add `pn.coord_flip()` for horizontal bars/intervals; use ordinary plotnine scales
111
+ for dollars, percentages, limits, or log axes. The default font is Times New Roman when installed. The theme checks for
112
+ DejaVu Serif, DejaVu Sans, STIXGeneral, and other available families before
113
+ rendering. An empty font list triggers registration of the bundled DejaVu Serif.
114
+ Override fonts, dimensions, or text size with
115
+ `theme_workforce(base_family=..., base_size=..., width=..., height=...)`.
116
+ For example, `base_family="DejaVu Sans"` selects sans-serif type.
117
+ Use `title=` for a plot title. Add logos, notes, and paper-specific annotations
118
+ with plotnine.
119
+
120
+ ## Paper defaults
121
+
122
+ - Times New Roman when available, 12-point text, 1.2 line spacing, and an
123
+ 8-by-5-inch canvas.
124
+ - Gray 0.54-point axes/ticks, 10-point axis-title padding in both directions,
125
+ 2% outer margins, 4.14-point ticks, no grid, and an inside upper-left vertical
126
+ legend with a transparent background.
127
+ - Dots use plotnine size 3.75. Legend dots are 25% larger; connected-line plots
128
+ show dots in the legend when points are enabled and lines otherwise.
129
+ - Confidence intervals use a 0.54-point stroke. Dots and interval strokes are
130
+ separate layers, so changing one does not change the other.
131
+
132
+ All five functions accept `title=` for a centered plot title. Grouped bars,
133
+ validation plots, and intervals on categorical axes put the legend above the panel.
134
+ For longer category names, supply
135
+ labels with line breaks or use `scale_x_discrete(labels=...)` to wrap them.
136
+ Datetime x-axes covering less than a day show clock times in the data's time zone.
137
+
138
+ Point-based functions accept `point_size`. Those with intervals also accept
139
+ `ci_width` (stroke width in points) and `cap_width` (plot-axis units
140
+ perpendicular to the interval). Caps default to 1% of the numeric axis span
141
+ or 0.12 category units on a categorical axis. A single numeric x position
142
+ has no default caps. On a log axis, the cap width
143
+ uses the transformed axis units. Set `cap_width=0` to omit caps. Grouped
144
+ `plot_intervals` narrows the default caps when x positions are closely spaced.
145
+
146
+ Dollar formatting is optional, rather than imposed on every outcome:
147
+
148
+ ```python
149
+ from workforce_plotting import dollars
150
+
151
+ p += pn.scale_y_continuous(labels=dollars) # -$1K, $0, $2.5K, ...
152
+ ```
153
+
154
+ `plot_validation` keeps its existing name and rectangular shape. Both axes
155
+ share numeric limits, but equal physical scaling is not imposed.
156
+
157
+ Titles remain ordinary plotnine labels. Move the legend without changing the
158
+ plot constructor or shared theme:
159
+
160
+ ```python
161
+ p += pn.labs(title="Earnings Before and After Enrollment")
162
+ p += pn.theme(legend_position="inside", legend_position_inside=(0.97, 0.97),
163
+ legend_justification_inside=(1, 1)) # upper-right
164
+ ```
165
+
166
+ To put it below the figure, use
167
+ `pn.theme(legend_position="bottom", legend_direction="horizontal")`.
168
+
169
+ ## Event-study recipe
170
+
171
+ Use `plot_lines` with supplied estimates and confidence bounds, then add the
172
+ reference lines explicitly. Here treatment begins at event year zero; a zero-effect
173
+ line is added, but no treatment-timing line is imposed:
174
+
175
+ ```python
176
+ p = (
177
+ plot_lines(df, x="event_year", y="effect", lower="lower", upper="upper")
178
+ + pn.geom_hline(yintercept=0, color="#A0A0A0", size=0.54)
179
+ + pn.scale_y_continuous(labels=dollars)
180
+ + pn.labs(x="Years Relative to Treatment", y="Earnings Effect")
181
+ )
182
+ ```
183
+
184
+ For unconnected cohort estimates plus a supplied curve, use
185
+ `plot_scatter(df, x="year", y="effect", lower="lower", upper="upper", fitted=curve)`.
186
+ For estimates across categories, use `plot_intervals`. Pass `fitted=` to draw a
187
+ curve from supplied values. For a single series, a supplied curve appears in teal
188
+ with gray points in both `plot_intervals` and `plot_scatter`.
189
+
190
+ ## Styling your own plots
191
+
192
+ Use the theme and colors without using the plot constructors. `WFColors` is an
193
+ alias of `oi_tools.figures.OIColors`, and `theme_workforce` builds on `theme_oi`.
194
+ The `oi-tools` dependency remains; you only need workforce imports in your code.
195
+ All plotting functions and styling live together in `workforce_plotting/figures.py`.
196
+
197
+ ```python
198
+ import polars as pl
199
+ import plotnine as pn
200
+ from workforce_plotting import theme_workforce, WFColors
201
+
202
+ df = pl.DataFrame({"year": [2020, 2021, 2022], "earnings": [20000, 23000, 25000]})
203
+ p = (
204
+ pn.ggplot(df.to_pandas(), pn.aes(x="year", y="earnings"))
205
+ + pn.geom_line(color=WFColors.TEAL)
206
+ + pn.geom_point(color=WFColors.TEAL)
207
+ + theme_workforce()
208
+ + pn.labs(x="Year", y="Annual earnings")
209
+ )
210
+ p.save("earnings.svg")
211
+ ```
212
+
213
+ Plot constructors accept Polars directly. When building a plotnine plot yourself,
214
+ the explicit conversion above works with the supported plotnine version.
215
+
216
+ ## Default outputs
217
+
218
+ `examples/default_examples.py` draws all five functions with their basic calls:
219
+ no added reference lines, titles, labels, scales, coordinates, or theme overrides.
220
+ It uses the same data for scatter and validation so their default behavior can
221
+ be compared directly. All values are invented.
222
+
223
+ ```bash
224
+ python examples/default_examples.py outputs/defaults
225
+ ```
226
+
227
+ Titles remain available through `pn.labs(title=...)`; the plain default examples
228
+ deliberately do not add them.
229
+
230
+ ## Editable examples
231
+
232
+ `examples/paper_examples.py` contains synthetic recipes for the paper/deck plot
233
+ families. These are invented values, not research results.
234
+
235
+ ```bash
236
+ python examples/paper_examples.py outputs/examples
237
+ pytest
238
+ ```
239
+
240
+ ## Changes in 0.4
241
+
242
+ - Validation plots accept `series=` to color by program or another grouping column.
243
+ - Plot titles are larger and centered, confidence intervals have short caps by
244
+ default, and interval plots accept a supplied fit.
245
+ - Numeric group labels, sparse groups, missing estimates, and intraday axes
246
+ render more reliably.
247
+
248
+ ## Changes in 0.3
249
+
250
+ - Paper defaults: Times New Roman, inside vertical legends, five-point ticks,
251
+ shared margins, and consistent axis-title spacing. Choose a different font
252
+ explicitly with `theme_workforce(base_family=...)` for deck-style figures.
253
+ - Consistent dots, larger legend dots, and independently sized intervals.
254
+ - Optional scatter confidence intervals and an optional `dollars` labeler.
255
+ - Complete function help plus plain-default and customized example scripts.
256
+
257
+ The five plot names and the rectangular validation layout are unchanged.
258
+
259
+ ## Changes from 0.1
260
+
261
+ This is a fresh API. The old Matplotlib functions, plotting dataclasses, curve
262
+ fitting machinery, and `aipw_analysis` compatibility package have been removed.
263
+ Plot creation and saving are now separate. The public API consists of the five plot functions, `theme_workforce`, `WFColors`, and the optional `dollars` formatter.
@@ -0,0 +1,7 @@
1
+ workforce_plotting/__init__.py,sha256=WMPL6dhkaVLCxJPSb516VWcVSjsI2R_UMYIjwfOe4R4,344
2
+ workforce_plotting/figures.py,sha256=UKGf0Ew6BkuQGosousroA-YxHHMX1EdxtoFrzKmPR_0,17644
3
+ workforce_plotting-0.4.0.dist-info/licenses/LICENSE,sha256=vIUOXKFifh8J0Pb7KgpB0HKgiKPfoMcz9zAqUHKl8mo,1076
4
+ workforce_plotting-0.4.0.dist-info/METADATA,sha256=nfpBuMKKLA3YN8gz7zIsrdFziXr6mdNb5ZAc2RXDgBs,10943
5
+ workforce_plotting-0.4.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
+ workforce_plotting-0.4.0.dist-info/top_level.txt,sha256=VBDPtAcqz3Z46cgEzdq8GGm8YIFQtkNcI1Zv8pqqcu4,19
7
+ workforce_plotting-0.4.0.dist-info/RECORD,,
@@ -1,135 +0,0 @@
1
- Metadata-Version: 2.4
2
- Name: workforce-plotting
3
- Version: 0.2.0
4
- Summary: Simple plotnine figures with Opportunity Insights styling.
5
- Author: Corey Gelb-Bicknell
6
- License-Expression: MIT
7
- Project-URL: Repository, https://github.com/coreygb1/workforce-plotting
8
- Requires-Python: >=3.12
9
- Description-Content-Type: text/markdown
10
- License-File: LICENSE
11
- Requires-Dist: plotnine<0.16,>=0.15
12
- Requires-Dist: pandas>=2.2
13
- Requires-Dist: oi-tools>=0.11.7
14
- Provides-Extra: polars
15
- Requires-Dist: polars>=1; extra == "polars"
16
- Requires-Dist: pyarrow>=14; extra == "polars"
17
- Provides-Extra: dev
18
- Requires-Dist: pytest>=8; extra == "dev"
19
- Requires-Dist: build; extra == "dev"
20
- Requires-Dist: twine; extra == "dev"
21
- Requires-Dist: polars>=1; extra == "dev"
22
- Requires-Dist: pyarrow>=14; extra == "dev"
23
- Dynamic: license-file
24
-
25
- # workforce-plotting
26
-
27
- Five small plotnine functions with a shared Opportunity Insights style. Supply
28
- prepared estimates and confidence bounds; the functions only draw them. Every
29
- function returns a `plotnine.ggplot` that you can edit with ordinary layers.
30
-
31
- ## Install
32
-
33
- Python 3.12 or newer is required (matching `oi-tools`). For a Polars workflow:
34
-
35
- ```bash
36
- uv add 'workforce-plotting[polars]'
37
- ```
38
-
39
- Or use pip:
40
-
41
- ```bash
42
- pip install 'workforce-plotting[polars]'
43
- ```
44
-
45
- For local development from this checkout:
46
-
47
- ```bash
48
- pip install -e '.[dev]'
49
- ```
50
-
51
- For Polars input, install the `polars` extra, which also supplies the Arrow
52
- conversion dependency. Pandas input needs no extra.
53
-
54
- ## Functions
55
-
56
- | Function | Use |
57
- |---|---|
58
- | `plot_lines(data, x=..., y=..., series=...)` | Event studies, trajectories, cohort trends, model complexity |
59
- | `plot_validation(data, x=..., y=...)` | RCT versus digital-twin estimates with an identity line |
60
- | `plot_bars(data, x=..., y=..., series=...)` | Already-calculated values by category |
61
- | `plot_scatter(data, x=..., y=..., fitted=...)` | Points with an optional precomputed fitted line |
62
- | `plot_intervals(data, x=..., y=..., lower=..., upper=...)` | Estimates and supplied confidence intervals |
63
- | `theme_workforce()` | Shared white background, gray axes, sans-serif type, no grid |
64
-
65
- `plot_lines` accepts `lower` and `upper` columns and `points=False`.
66
- `plot_validation` accepts `x_lower`, `x_upper`, `y_lower`, `y_upper`,
67
- `gaps="horizontal"` or `"vertical"`, and a common `(min, max)` pair of `limits`.
68
- The identity line has slope one in data units; the panel follows the figure's
69
- aspect ratio. Other functions accept `series` for discrete groups. Use ordered
70
- categorical columns to control color/legend order. Colors are teal, orange, navy,
71
- purple, blue, red, and dark green from the public `oi_tools.figures.OIColors` API.
72
- For a different mapping, add a plotnine manual color or fill scale.
73
-
74
- ```python
75
- import plotnine as pn
76
- from workforce_plotting import plot_lines
77
-
78
- p = plot_lines(df, x="year", y="earnings", series="group")
79
- p += pn.labs(x="Years since enrollment", y="Mean annual earnings")
80
- p.save("earnings.svg")
81
- ```
82
-
83
- Dataframes should be tidy: one row per plotted point, with separate columns for
84
- x, y, and an optional series. Lines connect points in x order within each series.
85
- Include a row with a missing y where a line should break; simply omitting a row
86
- connects the remaining observations. Fitted lines use the same column names as
87
- the scatter data. No smoothing, RMSE calculation, confidence-interval estimation,
88
- or automatic saving happens inside the plotting functions.
89
-
90
- Add `pn.coord_flip()` for horizontal bars/intervals; use ordinary plotnine scales
91
- for dollars, percentages, limits, or log axes. Fonts, dimensions, and text size
92
- use Lucida Sans when installed and DejaVu Sans otherwise. They can be overridden with `theme_workforce(base_family=..., base_size=..., width=..., height=...)`.
93
- Titles, logos, notes, and paper-specific annotations belong in the example/caller.
94
-
95
- ## Styling your own plots
96
-
97
- Use the theme and colors without using the plot constructors. `WFColors` is an
98
- alias of `oi_tools.figures.OIColors`, and `theme_workforce` builds on `theme_oi`.
99
- The `oi-tools` dependency remains; you only need workforce imports in your code.
100
- All plotting functions and styling live together in `workforce_plotting/figures.py`.
101
-
102
- ```python
103
- import polars as pl
104
- import plotnine as pn
105
- from workforce_plotting import theme_workforce, WFColors
106
-
107
- df = pl.DataFrame({"year": [2020, 2021, 2022], "earnings": [20000, 23000, 25000]})
108
- p = (
109
- pn.ggplot(df.to_pandas(), pn.aes(x="year", y="earnings"))
110
- + pn.geom_line(color=WFColors.TEAL)
111
- + pn.geom_point(color=WFColors.TEAL)
112
- + theme_workforce()
113
- + pn.labs(x="Year", y="Annual earnings")
114
- )
115
- p.save("earnings.svg")
116
- ```
117
-
118
- Plot constructors accept Polars directly. When building a plotnine plot yourself,
119
- the explicit conversion above works with the supported plotnine version.
120
-
121
- ## Editable examples
122
-
123
- `examples/paper_examples.py` contains synthetic recipes for the paper/deck plot
124
- families. These are invented values, not research results.
125
-
126
- ```bash
127
- python examples/paper_examples.py outputs/examples
128
- pytest
129
- ```
130
-
131
- ## Changes from 0.1
132
-
133
- This is a fresh API. The old Matplotlib functions, plotting dataclasses, curve
134
- fitting machinery, and `aipw_analysis` compatibility package have been removed.
135
- Plot creation and saving are now separate. The public API consists of the five plot functions, `theme_workforce`, and `WFColors`.
@@ -1,7 +0,0 @@
1
- workforce_plotting/__init__.py,sha256=Hu7rBJz6wdcIAn84s62-xTZFlz_bTee-3xIDd8u87s8,324
2
- workforce_plotting/figures.py,sha256=YHXf-PC349SgBXOTJhI4GZZcvPjJmZvP2xEC0eMWMiQ,6978
3
- workforce_plotting-0.2.0.dist-info/licenses/LICENSE,sha256=vIUOXKFifh8J0Pb7KgpB0HKgiKPfoMcz9zAqUHKl8mo,1076
4
- workforce_plotting-0.2.0.dist-info/METADATA,sha256=llHdwfUYE9Osn3Mp6uAQvfzOCxxOP-rnyKyep6TsJK4,5309
5
- workforce_plotting-0.2.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
6
- workforce_plotting-0.2.0.dist-info/top_level.txt,sha256=VBDPtAcqz3Z46cgEzdq8GGm8YIFQtkNcI1Zv8pqqcu4,19
7
- workforce_plotting-0.2.0.dist-info/RECORD,,