diff --git a/great_tables/_helpers.py b/great_tables/_helpers.py index 2c4f351a9..29b836b46 100644 --- a/great_tables/_helpers.py +++ b/great_tables/_helpers.py @@ -1051,6 +1051,75 @@ def define_units(units_notation: str) -> UnitDefinitionList: ) ) ``` + + Examples + -------- + + Let’s demonstrate a use case where we utilize `define_units()` to render an equation as + the subtitle in the table header, which currently doesn’t accept unit notation as input. + + We'll start by creating a Polars DataFrame representing the calculations of the equation + $y= a_2x^2 + a_1x + a_0$. + + ```{python} + #| code-fold: true + + import polars as pl + from great_tables import GT, html, define_units + + df = pl.DataFrame( + {"x": [1, 2, 3], "a2": [2, 3, 4], "a1": [3, 4, 5], "a0": [4, 5, 6]} + ).with_columns( + y=( + pl.col("a2").mul(pl.col("x").pow(2)) + + pl.col("a1").mul(pl.col("x")) + + pl.col("a0") + ) + ) + + df + ``` + + If we try to use unit annotations to format the equation as the subtitle in the header, it + won’t work as expected: + + ```{python} + ( + GT(df) + .cols_label(a2="{{a_2}}", a1="{{a_1}}", a0="{{a_0}}") + .tab_header(title="Linear Algebra", subtitle="y={{a_2}}{{x^2}}+{{a_1}}x+{{a_0}}") + ) + ``` + + To address this, we can create a small helper function, `u2html()`, which wraps a given string + in `define_units()` and emits the units to HTML. Next, we can build the subtitle by applying + `u2html()` to the string with unit annotations. Finally, we pass the assembled subtitle string + through `html()` to ensure it renders correctly. + + ```{python} + def u2html(x: str) -> str: + return define_units(x).to_html() + + + subtitle = ( + "y" + + "=" + + u2html("{{a_2}}") + + u2html("{{x^2}}") + + "+" + + u2html("{{a_1}}") + + "x" + + "+" + + u2html("{{a_0}}") + ) + + ( + GT(df) + .cols_label(a2="{{a_2}}", a1="{{a_1}}", a0="{{a_0}}") + .tab_header(title="Linear Algebra", subtitle=html(subtitle)) + ) + ``` + """ # Get a list of raw tokens