LaTeX output

For task-oriented examples, see the LaTeX guides.

Top-level document and plot builders

Public surface for the LaTeX table and TikZ plot builders.

Exports resolve lazily (PEP 562): from gerrytools.latex import TexTable imports only the table stack, and the TikZ plot classes load on first access.

class gerrytools.latex.TexDocument[source]

Bases: object

Class for creating and previewing LaTeX documents.

Allows adding packages, commands, and colors, and can render the LaTeX content to a PNG for display in Jupyter or a Qt window.

Variables:
  • body_string (str) – The LaTeX document body content.

  • package_list (list[str]) – List of LaTeX packages to include.

  • extra_package_commands (list[str]) – Additional LaTeX package commands.

  • command_list (list[str]) – List of custom LaTeX commands.

  • color_dict (dict[str, LatexColorSpec]) – Dictionary of color definitions.

  • engine_preference_order (tuple[str, ...]) – Preferred order of TeX engines to use.

add_color(color_name: str, color: str | tuple[int | float, int | float, int | float]) None[source]

Adds a custom color definition to the document.

Examples

tex_preview.add_color(“myblue”, (0.0, 0.0, 1.0)) tex_preview.add_color(“brand”, “tab:blue”) tex_preview.add_color(“accent”, “red!60!black”)

Parameters:
  • color_name (str) – The name of the color to define.

  • color (Color) – xcolor expression, HEX string, parseable named color, or RGB tuple. RGB tuple values must all be in [0, 1] or all be in [0, 255].

Returns:

None

Raises:

ValueError – If color_name is not a safe LaTeX identifier or color is not a valid xcolor expression/HEX/RGB value.

add_command(command: str) None[source]

Adds a custom LaTeX command to the document.

Examples

tex_preview.add_command(r”newcommand{R}{mathbb{R}}”)

Parameters:

command (str) – The LaTeX command to add.

Returns:

None

add_package_with_options(package_name: str, options: str | list[str]) None[source]

Adds a LaTeX package with options to the extra package commands.

The optioned form supersedes any plain \usepackage{name} entry, and re-registering the same package replaces its previous options.

Examples

tex_preview.add_package_with_options(“geometry”, “margin=1in”) tex_preview.add_package_with_options(“hyperref”, [“colorlinks”, “linkcolor=blue”])

Parameters:
  • package_name (str) – The name of the LaTeX package to add.

  • options (str | list[str]) – A single option string or a list of option strings.

Returns:

None

add_packages(packages: str | list[str]) None[source]

Adds one or more LaTeX packages to the package list.

A package already registered with options via add_package_with_options() is skipped since loading the same package twice with different options is a LaTeX “option clash” error.

Examples

tex_preview.add_packages(“geometry”) tex_preview.add_packages([“geometry”, “hyperref”])

Parameters:

packages (str | list[str]) – A single package name or a list of package names to add.

Returns:

None

compile_passes: int

Number of LaTeX passes per compile. Packages that persist node positions in the aux file (e.g. nicematrix) need 2.

property preamble: str

Build the LaTeX preamble for this document.

Returns:

LaTeX preamble string including document class, packages, and color

definitions.

Return type:

str

Raises:

ValueError – If a registered package option or color definition is invalid.

save_pdf(filepath: str | Path) None[source]

Saves the rendered LaTeX document as a PDF file.

Parameters:

filepath (str | Path) – The file path to save the PDF to.

Returns:

None

Raises:
  • TypeError – If filepath is not a string or Path.

  • ValueError – If filepath does not end in .pdf.

  • FileNotFoundError – If the destination directory does not exist.

  • RuntimeError – If LaTeX compilation fails or no TeX engine is available.

save_png(filepath: str | Path) None[source]

Saves the rendered LaTeX document as a PNG file.

Parameters:

filepath (str | Path) – The file path to save the PNG to.

Returns:

None

Raises:
to_tex() str[source]

The complete, compilable LaTeX document source.

The returned string is a standalone document (preamble, commands, body) that can be pasted directly into a .tex file and compiled, or copied piecewise into an existing report.

Returns:

The full document source.

Return type:

str

class gerrytools.latex.TexTable(df: DataFrame, *, use_defaults: bool = True)[source]

Bases: _TableBase

Class for generating LaTeX table code from a pandas DataFrame.

Parameters:
  • df (pd.DataFrame) – The DataFrame to be converted to a LaTeX table

  • use_defaults (bool, optional) – Whether to initialize with default table options (bold headers, 4 decimal places, etc.). Defaults to True.

Variables:

df (pd.DataFrame) – The DataFrame to be converted to a LaTeX table

Initialize the table builder from a DataFrame.

Parameters:
  • df (pd.DataFrame) – The DataFrame to convert to a LaTeX table. A copy is stored, so later edits to the original frame do not affect the table.

  • use_defaults (bool, optional) – Whether to seed the report-style defaults (bold headers, a double rule below the header, 4 decimal places). Defaults to True.

class gerrytools.latex.TikzPaintballPlot(vote_share_data: Iterable[float], seats_data: Iterable[float], total_seats: int | None = None)[source]

Bases: _TikzPlotBase

Class for generating paintball plots in TikZ/LaTeX.

The paintball plot places vote share on x and seat share on y in the unit square. Vote shares are expected in [0, 1]. Seat data is either interpreted as shares in [0, 1] or normalized from seat counts using total_seats. Guide lines are added with add_efficiency_gap_line(), add_proportionality_line(), or add_lines_with_slope().

Initialize a LaTeX paintball plot.

Parameters:
  • vote_share_data (Iterable[float]) – Vote-share values for each plan outcome. Every value must be in [0, 1].

  • seats_data (Iterable[float]) – Seat-share values or seat counts for each plan outcome. If total_seats is None, values are interpreted as seat shares and must be in [0, 1]. If total_seats is provided, values are interpreted as seat counts and normalized by dividing by total_seats.

  • total_seats (int | None, optional) – Maximum seat count used to normalize seats_data when seat counts are provided. Defaults to None.

add_efficiency_gap_line(*, linecolor: str | tuple[int | float, int | float, int | float] | None = 'gray', linewidth: float = 1.0, linestyle: str = 'solid', name: str = 'efficiency_gap') None[source]

Add the standard efficiency-gap guide line (slope 2 through (0.5, 0.5)).

Parameters:
  • linecolor (Color | None, optional) – Line color. Pass None for a transparent line. Defaults to “gray”.

  • linewidth (float, optional) – Line width. Defaults to 1.0.

  • linestyle (str, optional) – Line style (Matplotlib token or TikZ style). Defaults to “solid”.

  • name (str, optional) – Name the line is stored under. Defaults to “efficiency_gap”.

add_lines_with_slope(slopes: Iterable[float], linecolor: str | tuple[int | float, int | float, int | float] | None = 'black', linewidth: float = 1.0, linestyle: str = 'solid', *, name: str | None = None) None[source]

Adds lines with specified slopes to the paintball plot.

Parameters:
  • slopes (Iterable[float]) – The slopes of the lines to be added.

  • linecolor (Color | None, optional) – The color of the lines. Pass None for transparent lines. Defaults to “black”.

  • linewidth (float, optional) – The width of the lines. Defaults to 1.0

  • linestyle (str, optional) – The style of the lines (Matplotlib token or TikZ style). Defaults to “solid”.

  • name (str | None, optional) – An optional name for the line. If provided, the line can be referenced later by this name. Defaults to None.

add_proportionality_line(*, linecolor: str | tuple[int | float, int | float, int | float] | None = 'gray', linewidth: float = 1.0, linestyle: str = 'dashed', name: str = 'proportionality') None[source]

Add the standard proportionality guide line (slope 1 through (0.5, 0.5)).

Parameters:
  • linecolor (Color | None, optional) – Line color. Pass None for a transparent line. Defaults to “gray”.

  • linewidth (float, optional) – Line width. Defaults to 1.0.

  • linestyle (str, optional) – Line style (Matplotlib token or TikZ style). Defaults to “dashed”.

  • name (str, optional) – Name the line is stored under. Defaults to “proportionality”.

add_seats_votes_data(vote_share_data: Iterable[float], seats_data: Iterable[float], *, total_seats: int | None = None) None[source]

Add vote-share / seat-share data points to the paintball plot.

Parameters:
  • vote_share_data (Iterable[float]) – Vote-share values to add. Every value must be in [0, 1].

  • seats_data (Iterable[float]) – Seat-share values or seat counts to add. If total_seats is None, values are interpreted as seat shares and must be in [0, 1]. If total_seats is provided, values are interpreted as seat counts and normalized by dividing by total_seats.

  • total_seats (int | None, optional) – The maximum number of seats. If provided, seats_data will be scaled by this value to obtain seat shares. If None, seats_data is assumed to already be in seat share format (i.e., in [0, 1]).

clear_lines() None[source]

Clears all added lines from the paintball plot.

property hull_document: TexDocument

Return the LaTeX document for the hull-based paintball plot.

Returns:

Document object containing hull-rendered TikZ code.

Return type:

TexDocument

options: PaintballOptions
print(*, hull: bool = False) None[source]

Print the generated TikZ body to stdout.

Parameters:

hull (bool, optional) – If True, print the hull-rendered plot; otherwise print the point-rendered plot. Defaults to False.

Returns:

None

set_crosshair_options(color: str | tuple[int | float, int | float, int | float] | None, width: float) None[source]

Sets the crosshair options for the paintball plot.

Parameters:
  • color (Color | None) – The color of the crosshair. None removes it.

  • width (float) – The width of the crosshair lines.

set_hull_options(color: str | tuple[int | float, int | float, int | float] | None | Unset = Unset.token, alpha: float | None | Unset = Unset.token, edgecolor: str | tuple[int | float, int | float, int | float] | None | Unset = Unset.token, edgewidth: float | None | Unset = Unset.token, edgealpha: float | None | Unset = Unset.token) None[source]

Sets the hull options for the paintball plot.

Omitted keywords leave the current setting unchanged. For colors, passing None removes the fill or edge. Alpha and width retain their existing behavior: passing None restores inheritance from the corresponding marker option.

Parameters:
  • color (Color | None | Unset) – The fill color of the hull; None removes the fill. Defaults to UNSET (leave unchanged).

  • alpha (float | None | Unset) – The opacity of the hull fill (0.0 to 1.0); None inherits markeralpha. Defaults to UNSET (leave unchanged).

  • edgecolor (Color | None | Unset) – The edge color of the hull; None removes the edge. Defaults to UNSET (leave unchanged).

  • edgewidth (float | None | Unset) – The edge width of the hull in points; None inherits markeredgewidth. Defaults to UNSET (leave unchanged).

  • edgealpha (float | None | Unset) – The edge opacity of the hull (0.0 to 1.0); None inherits markeredgealpha. Defaults to UNSET (leave unchanged).

set_marker_options(size: float | None = None, color: str | tuple[int | float, int | float, int | float] | None | Unset = Unset.token, alpha: float | None = None, edgecolor: str | tuple[int | float, int | float, int | float] | None | Unset = Unset.token, edgewidth: float | None = None, edgealpha: float | None = None) None[source]

Sets the marker options for the paintball plot.

Parameters:
  • size (float | None, optional) – The size of the markers in points. If None, the size is not changed from the previous setting. Defaults to None.

  • color (Color | None | Unset, optional) – The color of the markers. None removes the fill; omission retains the current color. Defaults to UNSET.

  • alpha (float | None, optional) – The opacity of the markers (0.0 to 1.0). If None, the opacity is not changed from the previous setting. Defaults to None.

  • edgecolor (Color | None | Unset, optional) – The edge color of the markers. None removes the edge; omission retains the current color. Defaults to UNSET.

  • edgewidth (float | None, optional) – The edge width of the markers. If None, the edge width is not changed from the previous setting. Defaults to None.

  • edgealpha (float | None, optional) – The edge opacity of the markers (0.0 to 1.0). If None, the edge opacity is not changed from the previous setting. Defaults to None.

class gerrytools.latex.TikzSeatsVotesPlot(*, legend: bool = False, xlabel: str | None = None, ylabel: str | None = None, title: str | None = None)[source]

Bases: _TikzPlotBase

Generate seats-votes plots as TikZ/LaTeX.

Initialize a LaTeX seats-votes plot.

The plot renders at the options’ xscale/yscale (10 by 10 TikZ units by default); use set_scale() to change the drawn size.

Parameters:
  • legend (bool, optional) – Whether to include a legend. Defaults to False.

  • xlabel (str | None, optional) – X-axis label text. Defaults to None.

  • ylabel (str | None, optional) – Y-axis label text. Defaults to None.

  • title (str | None, optional) – Plot title text. Defaults to None.

add_custom_line(slope: float, *, linecolor: str | tuple[int | float, int | float, int | float] | None, linestyle: str, linewidth: float, name: str | None = None) None[source]

Add a custom slope-constrained line passing through (0.5, 0.5).

Parameters:
  • slope (float) – Line slope.

  • linecolor (Color | None) – Line color. None makes the line transparent.

  • linestyle (str) – Line style (Matplotlib token or TikZ style).

  • linewidth (float) – Line width.

  • name (str | None, optional) – Legend label; unlabeled lines are drawn but do not appear in the legend. Defaults to None.

add_efficiency_gap_line(*, linecolor: str | tuple[int | float, int | float, int | float] | None = 'gray', linestyle: str = 'solid', linewidth: float = 1.0, name: str | None = None) None[source]

Add an efficiency-gap line (y=2x-0.5) to the plot.

Parameters:
  • linecolor (Color | None, optional) – Line color. Pass None for a transparent line. Defaults to “gray”.

  • linestyle (str, optional) – Line style (Matplotlib token or TikZ style). Defaults to “solid”.

  • linewidth (float, optional) – Line width. Defaults to 1.0.

  • name (str | None, optional) – Legend label. Defaults to “Efficiency Gap”.

add_election(target_party_vote_shares: Sequence[int | float], total_votes: Sequence[int | float] | None = None, *, name: str | None = None, linecolor: str | tuple[int | float, int | float, int | float] | None | Unset = Unset.token, markercolor: str | tuple[int | float, int | float, int | float] | None | Unset = Unset.token, marker_label: str | None = None) None[source]

Add a seats-votes curve to the plot.

Parameters:
  • target_party_vote_shares (Sequence[int | float]) – Per-district vote totals or vote shares for the party of interest. If total_votes is None, these are interpreted as vote shares and must be in [0, 1].

  • total_votes (Sequence[int | float] | None, optional) – Per-district total vote totals. If None, all totals are treated as 1.0 and target_party_vote_shares is interpreted as vote shares. Defaults to None.

  • name (str | None, optional) – Legend label for the seats-votes curve. Defaults to None.

  • linecolor (Color | None | Unset, optional) – Curve color. None removes the line; omission uses self.standard_election_color. Defaults to UNSET.

  • markercolor (Color | None | Unset, optional) – Election-result marker color. None removes the marker; omission uses self.standard_marker_color. Defaults to UNSET.

  • marker_label (str | None, optional) – Legend label for election-result markers. Defaults to None.

Raises:

ValueError – If vote arrays are invalid or a share lies outside [0, 1].

add_proportionality_line(*, linecolor: str | tuple[int | float, int | float, int | float] | None = 'gray', linestyle: str = 'dashed', linewidth: float = 1.0, name: str | None = None) None[source]

Add a proportionality line (y=x) to the plot.

Parameters:
  • linecolor (Color | None, optional) – Line color. Pass None for a transparent line. Defaults to “gray”.

  • linestyle (str, optional) – Line style (Matplotlib token or TikZ style). Defaults to “dashed”.

  • linewidth (float, optional) – Line width. Defaults to 1.0.

  • name (str | None, optional) – Legend label. Defaults to “Proportionality”.

clear_options() None[source]

Reset seats-votes options to defaults and restore the default crosshairs.

display_additional_lines_in_legend(enabled: bool) None[source]

Set whether additional guide lines appear in the legend.

Parameters:

enabled (bool) – Whether to include guide lines in the legend.

display_election_markers(enabled: bool) None[source]

Set whether overall election-result markers are displayed.

Parameters:

enabled (bool) – Whether to display the markers.

options: SeatsVotesOptions
remove_crosshairs() None[source]

Remove crosshairs from the plot.

set_fontsize(fontsize: float) None[source]

Set a unified font size for the title, axis labels, and legend text.

Parameters:

fontsize (float) – Font size in points.

Returns:

None

set_label_fontsize(fontsize: float) None[source]

Set the font size used for the title and axis labels.

Parameters:

fontsize (float) – Font size in points.

Returns:

None

set_linewidth(linewidth: float) None[source]

Set seats-votes curve line width.

Parameters:

linewidth (float) – Line width in points.

Returns:

None

set_markersize(markersize: float) None[source]

Set election-result marker size.

Parameters:

markersize (float) – Marker size in points.

Returns:

None

update_crosshair_settings(*, x_width: float = 0.02, y_width: float = 0.02, color: str | tuple[int | float, int | float, int | float] | None = 'lightgrey', alpha: float = 1.0) None[source]

Configure centered crosshair bands.

Parameters:
  • x_width (float, optional) – Horizontal band width around x=0.5. Defaults to 0.02.

  • y_width (float, optional) – Vertical band width around y=0.5. Defaults to 0.02.

  • color (Color | None, optional) – Crosshair fill color. Pass None for transparent crosshairs. Defaults to "lightgrey".

  • alpha (float, optional) – Crosshair fill opacity in [0, 1]. Defaults to 1.0.

Returns:

None

class gerrytools.latex.TikzTable(df: DataFrame, *, use_defaults: bool = True)[source]

Bases: _TableBase

Generate a nicematrix NiceTabular table from a pandas DataFrame.

The builder API is identical to TexTable; both classes share one implementation and differ only in the TeX dialect they emit. The default output matches the visual appearance of TexTable: no cell borders, horizontal rules where \hline would appear, and vertical rules where | would appear in the tabular preamble. TikZ-specific extras let you control cell geometry, inject raw \draw commands, and set per-cell borders.

The generated document requires the nicematrix and tikz packages and two compiler passes (registered automatically at construction), because nicematrix records cell positions on the first pass and draws on the second.

Parameters:
  • df (pd.DataFrame) – Source data.

  • use_defaults (bool) – When True, bold column headers, 4 decimal places, and a double rule above the first data row are applied (the same defaults as TexTable).

Initialize the table builder from a DataFrame.

Parameters:
  • df (pd.DataFrame) – The DataFrame to convert to a LaTeX table. A copy is stored, so later edits to the original frame do not affect the table.

  • use_defaults (bool, optional) – Whether to seed the report-style defaults (bold headers, a double rule below the header, 4 decimal places). Defaults to True.

add_draw(draw_cmd: str) None[source]

Append a raw TikZ command to the table’s \\CodeAfter block.

Cells are addressable as (table-<row>-<col>) with the usual TikZ anchors, and the boundary lattice as (row-<i>) / (col-<j>).

Parameters:

draw_cmd (str) – A complete TikZ command, including the trailing semicolon.

clear_cell_borders() None[source]

Remove all per-cell border specifications.

clear_extra_draws() None[source]

Remove every command added with add_draw().

set_cell_border(row: int | list[int], col: int | list[int], sides: str | Iterable[str]) None[source]

Specify which borders to draw on individual cells.

The (row, col) indices are 1-based TikZ matrix coordinates — row 1 is the first rendered row (group-header or column-header), and column 1 is the leftmost column.

Parameters:
  • row (int | list[int]) – TikZ row index (or list of indices).

  • col (int | list[int]) – TikZ column index (or list of indices).

  • sides (str | Iterable[str]) – "top", "bottom", "left", "right" — or an iterable of them, or "all".

Raises:

ValueError – If a side is unsupported or a row or column index is out of bounds.

set_cell_space_limits(limit: str) None[source]

Set nicematrix’s minimal vertical space around cell content.

Parameters:

limit (str) – Literal LaTeX dimension (e.g. "2pt").

Raises:

ValueError – If limit is not a safe LaTeX dimension.

set_table_name(name: str) None[source]

Set the nicematrix name used to address this table’s cells in TikZ draws.

Cells become addressable as (<name>-<row>-<col>). The default is "table"; give each table a distinct name when pasting several TikzTable bodies into one document, since duplicate nicematrix names collide.

Parameters:

name (str) – PGF node-name prefix for the NiceTabular environment.

Raises:

ValueError – If name is not a safe PGF node-name prefix.

class gerrytools.latex.Unset(*values)[source]

Bases: Enum

Sentinel type distinguishing an omitted kwarg from an explicit None.

Kwargs where None is itself meaningful default to UNSET rather than None: an omitted kwarg keeps the stored/base value, while an explicit None is applied as a real value (for example “no fill/edge”, clearing a field back to its matplotlib default, or restoring inheritance in the LaTeX hull options). Both names are public because they appear in add_* and set_* signatures: wrappers forwarding those kwargs use UNSET as their own default and Unset in their annotations. Defined in this dependency-light hub so both the plotting and LaTeX packages share the same sentinel object.

token = 1
gerrytools.latex.latex_escape(text: str) str[source]

Escape LaTeX-special characters in plain text.

Parameters:

text (str) – Raw text to escape for safe LaTeX rendering.

Returns:

Escaped text with LaTeX control sequences for special characters.

Return type:

str

Table formatters

gerrytools.latex.formatters.CellWrapper

Formatter callback that receives (raw_value, rendered_text) and returns updated pair.

alias of Callable[[object, str], tuple[object, str]]

gerrytools.latex.formatters.IndexCellWrapper

Formatter callback for table index values.

alias of Callable[[Hashable, str], tuple[Hashable, str]]

gerrytools.latex.formatters.TableCellValue

Arbitrary DataFrame cell value used by table/formatter pipelines.

gerrytools.latex.formatters.TableIndexValue

Hashable index value used by table index-formatting callbacks.

gerrytools.latex.formatters.boxed_center(width: int, height: int | None = None, unit: str = 'mm') Callable[[object, str], tuple[object, str]][source]

Create a formatter that centers content in a fixed-size LaTeX \parbox.

Parameters:
  • width (int) – Box width value.

  • height (int | None, optional) – Box height value. If None, uses width. Defaults to None.

  • unit (str, optional) – LaTeX unit suffix for width/height (for example "mm"). Defaults to "mm".

Returns:

Formatter that wraps rendered text in a centered parbox.

Return type:

CellWrapper

gerrytools.latex.formatters.compose_formatters(*funcs: Callable[[object, str], tuple[object, str]]) Callable[[object, str], tuple[object, str]][source]

Compose multiple CellWrapper formatters into one formatter.

A cell fill (CellFillText) is carried as an effect rather than as text: after each step the fill spec is peeled off and accumulated (a later-applied fill overrides an earlier one), subsequent formatters see the plain rendered text, and the accumulated fill is re-attached to the final result. A wrapper composed around a fill formatter therefore wraps the text only, and the fill still reaches the table emitters.

Parameters:

*funcs (CellWrapper) – One or more formatter callables.

Returns:

A formatter that applies all provided formatters from right to left.

Return type:

CellWrapper

gerrytools.latex.formatters.diverging_gradient_formatter(lo: float = 0.0, mid: float = 0.5, hi: float = 1.0, color_lo: str | tuple[int | float, int | float, int | float] = 'darkpastelgreen', color_hi: str | tuple[int | float, int | float, int | float] = 'richlavender', color_mid: str | tuple[int | float, int | float, int | float] = 'white', *, command_name: str | None = 'divgrad', precision: int = 4) Callable[[object, str], tuple[object, str]][source]

Formatter that applies a diverging gradient cell background.

By default, renders numeric cells as compact LaTeX command calls like \divgrad{0.774} and exposes the matching preamble command so TexTable can add it automatically when the formatter is set.

Pass command_name=None to use the literal-color path instead. That computes the interpolated background color in Python and prepends a \cellcolor[HTML]{RRGGBB} to the rendered string. This is the preferred path for TikzTable, which routes the carried fill spec into nicematrix’s \CodeBefore so the fill spans the full cell.

Parameters:
  • lo (float) – Lower bound of the gradient range. Defaults to 0.0.

  • mid (float) – Midpoint of the gradient range. Defaults to 0.5.

  • hi (float) – Upper bound of the gradient range. Defaults to 1.0.

  • color_lo (Color) – Color at the lower bound. Defaults to "darkpastelgreen".

  • color_hi (Color) – Color at the upper bound. Defaults to "richlavender".

  • color_mid (Color) – Color at the midpoint. Defaults to "white".

  • command_name (str | None) – LaTeX command name for compact command-based output. Pass None for literal \cellcolor[HTML]{...} prefixes. Defaults to "divgrad".

  • precision (int) – siunitx round precision used by the generated command when command_name is provided. Defaults to 4.

Returns:

Formatter that applies gradient coloring to numeric cells.

Return type:

CellWrapper

Raises:

ValueError – If bounds, precision, a command name, or command-based colors are invalid.

gerrytools.latex.formatters.highlight_between(lower_bound: int | float, upper_bound: int | float, color: str | tuple[int | float, int | float, int | float] = 'yellow', *, round_to: int | None = None, include_lower: bool = True, include_upper: bool = True, command_prefix: str | None = None) Callable[[object, str], tuple[object, str]][source]

Highlight values between lower and upper bounds.

Parameters:
  • lower_bound (int | float) – Lower bound.

  • upper_bound (int | float) – Upper bound.

  • color (Color, optional) – Highlight color. Defaults to "yellow".

  • round_to (int | None, optional) – Decimal places for comparison rounding. Defaults to None.

  • include_lower (bool, optional) – Whether the lower bound is inclusive. Defaults to True.

  • include_upper (bool, optional) – Whether the upper bound is inclusive. Defaults to True.

  • command_prefix (str | None, optional) – Prefix for generated compact LaTeX commands. Pass None for literal \cellcolor output. Defaults to None.

Returns:

Highlight formatter.

Return type:

CellWrapper

gerrytools.latex.formatters.highlight_ge(thresh: int | float, color: str | tuple[int | float, int | float, int | float] = 'yellow', *, round_to: int | None = None, command_prefix: str | None = None) Callable[[object, str], tuple[object, str]][source]

Highlight values greater than or equal to a threshold.

Parameters:
  • thresh (int | float) – Threshold value.

  • color (Color, optional) – Highlight color. Defaults to "yellow".

  • round_to (int | None, optional) – Decimal places for comparison rounding. Defaults to None.

  • command_prefix (str | None, optional) – Prefix for generated compact LaTeX commands. Pass None for literal \cellcolor output. Defaults to None.

Returns:

Highlight formatter.

Return type:

CellWrapper

gerrytools.latex.formatters.highlight_gt(thresh: int | float, color: str | tuple[int | float, int | float, int | float] = 'yellow', *, round_to: int | None = None, command_prefix: str | None = None) Callable[[object, str], tuple[object, str]][source]

Highlight values strictly greater than a threshold.

Parameters:
  • thresh (int | float) – Threshold value.

  • color (Color, optional) – Highlight color. Defaults to "yellow".

  • round_to (int | None, optional) – Decimal places for comparison rounding. Defaults to None.

  • command_prefix (str | None, optional) – Prefix for generated compact LaTeX commands. Pass None for literal \cellcolor output. Defaults to None.

Returns:

Highlight formatter.

Return type:

CellWrapper

gerrytools.latex.formatters.highlight_le(thresh: float, color: str | tuple[int | float, int | float, int | float] = 'yellow', *, round_to: int | None = None, command_prefix: str | None = None) Callable[[object, str], tuple[object, str]][source]

Highlight values less than or equal to a threshold.

Parameters:
  • thresh (float) – Threshold value.

  • color (Color, optional) – Highlight color. Defaults to "yellow".

  • round_to (int | None, optional) – Decimal places for comparison rounding. Defaults to None.

  • command_prefix (str | None, optional) – Prefix for generated compact LaTeX commands. Pass None for literal \cellcolor output. Defaults to None.

Returns:

Highlight formatter.

Return type:

CellWrapper

gerrytools.latex.formatters.highlight_lt(thresh: float, color: str | tuple[int | float, int | float, int | float] = 'yellow', *, round_to: int | None = None, command_prefix: str | None = None) Callable[[object, str], tuple[object, str]][source]

Highlight values strictly less than a threshold.

Parameters:
  • thresh (float) – Threshold value.

  • color (Color, optional) – Highlight color. Defaults to "yellow".

  • round_to (int | None, optional) – Decimal places for comparison rounding. Defaults to None.

  • command_prefix (str | None, optional) – Prefix for generated compact LaTeX commands. Pass None for literal \cellcolor output. Defaults to None.

Returns:

Highlight formatter.

Return type:

CellWrapper

gerrytools.latex.formatters.latex_commands_for(formatter: Callable) tuple[str, ...][source]

Return LaTeX preamble commands required by a formatter.

Parameters:

formatter (Callable) – Formatter callable to inspect.

Returns:

Required LaTeX preamble command definitions.

Return type:

tuple[str, …]

gerrytools.latex.formatters.round_decimals(decimal_places: int) Callable[[object, str], tuple[object, str]][source]

Create a formatter that renders numeric values with fixed decimal places.

Parameters:

decimal_places (int) – Number of decimal places to render.

Returns:

Formatter that applies fixed-point rendering to numeric values.

Return type:

CellWrapper

gerrytools.latex.formatters.wrap_with_tex_command(cmd_str: str) Callable[[object, str], tuple[object, str]][source]

Wrap rendered cell text in a LaTeX command.

Parameters:

cmd_str (str) – LaTeX command name without a leading backslash.

Returns:

Formatter that renders output as \<cmd_str>{...}.

Return type:

CellWrapper

Command helpers

gerrytools.latex.commands.tex_cell_highlight_command(cmd_str: str, color: str | tuple[int | float, int | float, int | float] = 'yellow') str[source]

Generates a LaTeX command that applies a cell background color.

Emits \<cmd_str>{x}, which renders x with a \cellcolor prefix.

Parameters:
  • cmd_str (str) – The name of the LaTeX command to create.

  • color (Color, optional) – Cell background color. Defaults to "yellow".

Returns:

A string containing the LaTeX command definition.

Return type:

str

gerrytools.latex.commands.tex_diverging_gradient_command(cmd_str: str = 'heat', lo: float = 0.0, mid: float = 0.5, hi: float = 1.0, color_lo: str = 'darkpastelgreen', color_hi: str = 'richlavender', color_mid: str = 'white', precision: int = 4) str[source]

Generates a LaTeX command for diverging gradient coloring for numerical values in a table.

The generated command applies a gradient from color_lo at lo through color_mid at mid to color_hi at hi. Values are clamped to the interval [lo, hi].

Requires: xcolor[table], latexcolor, xfp, siunitx.

Parameters:
  • cmd_str (str, optional) – The name of the LaTeX command to create. Defaults to "heat".

  • lo (float, optional) – The lower bound of the numerical range. Defaults to 0.0.

  • mid (float, optional) – The midpoint of the numerical range. Defaults to 0.5.

  • hi (float, optional) – The upper bound of the numerical range. Defaults to 1.0.

  • color_lo (str, optional) – The color at the lower bound. Defaults to "darkpastelgreen".

  • color_hi (str, optional) – The color at the upper bound. Defaults to "richlavender".

  • color_mid (str, optional) – The color at the midpoint. Defaults to "white".

  • precision (int, optional) – Number of decimal places to round the number to. Defaults to 4.

Returns:

A string containing the LaTeX command definition to be added to preamble.

Return type:

str

gerrytools.latex.commands.tex_gradient_command(cmd_str: str = 'gradient', color_name: str = 'denim', lo: float = 0.0, hi: float = 1.0, precision: int = 4) str[source]

Generates a LaTeX command for gradient coloring of numerical values.

Emits a LaTeX command <cmd_str>{x} that colors the cell with a gradient of <color_name> from lo (full color) to hi (white). Values outside [lo, hi] are clamped, and a degenerate range (hi == lo) is guarded against division by zero, matching the two-color and diverging gradient commands.

Requires: xcolor (with [table]), colortbl, xfp, siunitx.

Parameters:
  • cmd_str (str, optional) – The name of the LaTeX command to create. Defaults to "gradient".

  • color_name (str, optional) – The name of the color to use for the gradient. Defaults to "denim".

  • lo (float, optional) – The lower bound of the numerical range. Defaults to 0.0.

  • hi (float, optional) – The upper bound of the numerical range. Defaults to 1.0.

  • precision (int, optional) – Number of decimal places to round the number to. Defaults to 4.

Returns:

A string containing the LaTeX command definition.

Return type:

str

gerrytools.latex.commands.tex_twocolor_gradient_command(cmd_str: str = 'heat', lo: float = 0.0, hi: float = 1.0, color_lo: str = 'denim', color_hi: str = 'alizarin', precision: int = 4) str[source]

Generates a LaTeX command for two-color gradient coloring of numerical values.

Emits a LaTeX command <cmd_str>{x} that colors the cell with a two-color gradient from color_lo (at lo) to color_hi (at hi), clamped outside the range.

Requires: xcolor (with [table]), colortbl, xfp, siunitx.

Note: color mixing is done in xcolor and is a linear interpolation by mixing saturation percentages of the two colors.

Parameters:
  • cmd_str (str, optional) – The name of the LaTeX command to create. Defaults to "heat".

  • lo (float, optional) – The lower bound of the numerical range. Defaults to 0.0.

  • hi (float, optional) – The upper bound of the numerical range. Defaults to 1.0.

  • color_lo (str, optional) – The color at the lower bound. Defaults to "denim".

  • color_hi (str, optional) – The color at the upper bound. Defaults to "alizarin".

  • precision (int, optional) – Number of decimal places to round the number to. Defaults to 4.

Returns:

A string containing the LaTeX command definition to be added to preamble.

Return type:

str

gerrytools.latex.commands.validate_command_name(cmd_str: str) None[source]

Validate that a LaTeX command name is legal.

Parameters:

cmd_str (str) – LaTeX command name without a leading backslash.

Returns:

None

Raises:

ValueError – If cmd_str starts with "\\" or contains non-letter characters.