Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: add an example demonstrating define_units() usage #446

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions great_tables/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading