Skip to content

Commit 06e6b6d

Browse files
jrycwmachowrich-iannone
authored
docs: add an example demonstrating define_units() usage (#446)
* Add an example demonstrating `define_units()` usage * Add `GT.cols_label()` --------- Co-authored-by: Michael Chow <mc_al_github@fastmail.com> Co-authored-by: Richard Iannone <riannone@me.com>
1 parent 1af68a3 commit 06e6b6d

1 file changed

Lines changed: 69 additions & 0 deletions

File tree

great_tables/_helpers.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1124,6 +1124,75 @@ def define_units(units_notation: str) -> UnitDefinitionList:
11241124
)
11251125
)
11261126
```
1127+
1128+
Examples
1129+
--------
1130+
1131+
Let’s demonstrate a use case where we utilize `define_units()` to render an equation as
1132+
the subtitle in the table header, which currently doesn’t accept unit notation as input.
1133+
1134+
We'll start by creating a Polars DataFrame representing the calculations of the equation
1135+
$y= a_2x^2 + a_1x + a_0$.
1136+
1137+
```{python}
1138+
#| code-fold: true
1139+
1140+
import polars as pl
1141+
from great_tables import GT, html, define_units
1142+
1143+
df = pl.DataFrame(
1144+
{"x": [1, 2, 3], "a2": [2, 3, 4], "a1": [3, 4, 5], "a0": [4, 5, 6]}
1145+
).with_columns(
1146+
y=(
1147+
pl.col("a2").mul(pl.col("x").pow(2))
1148+
+ pl.col("a1").mul(pl.col("x"))
1149+
+ pl.col("a0")
1150+
)
1151+
)
1152+
1153+
df
1154+
```
1155+
1156+
If we try to use unit annotations to format the equation as the subtitle in the header, it
1157+
won’t work as expected:
1158+
1159+
```{python}
1160+
(
1161+
GT(df)
1162+
.cols_label(a2="{{a_2}}", a1="{{a_1}}", a0="{{a_0}}")
1163+
.tab_header(title="Linear Algebra", subtitle="y={{a_2}}{{x^2}}+{{a_1}}x+{{a_0}}")
1164+
)
1165+
```
1166+
1167+
To address this, we can create a small helper function, `u2html()`, which wraps a given string
1168+
in `define_units()` and emits the units to HTML. Next, we can build the subtitle by applying
1169+
`u2html()` to the string with unit annotations. Finally, we pass the assembled subtitle string
1170+
through `html()` to ensure it renders correctly.
1171+
1172+
```{python}
1173+
def u2html(x: str) -> str:
1174+
return define_units(x).to_html()
1175+
1176+
1177+
subtitle = (
1178+
"y"
1179+
+ "="
1180+
+ u2html("{{a_2}}")
1181+
+ u2html("{{x^2}}")
1182+
+ "+"
1183+
+ u2html("{{a_1}}")
1184+
+ "x"
1185+
+ "+"
1186+
+ u2html("{{a_0}}")
1187+
)
1188+
1189+
(
1190+
GT(df)
1191+
.cols_label(a2="{{a_2}}", a1="{{a_1}}", a0="{{a_0}}")
1192+
.tab_header(title="Linear Algebra", subtitle=html(subtitle))
1193+
)
1194+
```
1195+
11271196
"""
11281197

11291198
# Get a list of raw tokens

0 commit comments

Comments
 (0)