Skip to content

Commit

Permalink
test cases for typst table css translation
Browse files Browse the repository at this point in the history
note oceanea is failing
  • Loading branch information
gordonwoodhull committed Apr 19, 2024
1 parent f1f2485 commit d415ca1
Show file tree
Hide file tree
Showing 11 changed files with 401 additions and 0 deletions.
36 changes: 36 additions & 0 deletions tests/docs/typst/tables/great-tables/air-quality.qmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
---
title: "Great Tables - Air Quality"
format: typst
keep-md: true
format-links: false
---

```{python}
from great_tables import GT, html
from great_tables.data import airquality
airquality_mini = airquality.head(10).assign(Year = 1973)
(
GT(airquality_mini)
.tab_header(
title="New York Air Quality Measurements",
subtitle="Daily measurements in New York City (May 1-10, 1973)"
)
.tab_spanner(
label="Time",
columns=["Year", "Month", "Day"]
)
.tab_spanner(
label="Measurement",
columns=["Ozone", "Solar_R", "Wind", "Temp"]
)
.cols_move_to_start(columns=["Year", "Month", "Day"])
.cols_label(
Ozone = html("Ozone,<br>ppbV"),
Solar_R = html("Solar R.,<br>cal/m<sup>2</sup>"),
Wind = html("Wind,<br>mph"),
Temp = html("Temp,<br>&deg;F")
)
)
```
23 changes: 23 additions & 0 deletions tests/docs/typst/tables/great-tables/islands.qmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
title: "Great Tables - Islands"
format: pptx
keep-md: true
format-links: false
---

```{python}
from great_tables import GT, md, html
from great_tables.data import islands
islands_mini = islands.head(10)
(
GT(islands_mini, rowname_col="name")
.tab_header(title="Large Landmasses of the World", subtitle="The top ten largest are presented")
.tab_source_note(source_note="Source: The World Almanac and Book of Facts, 1975, page 406.")
.tab_source_note(
source_note=md("Reference: McNeil, D. R. (1977) *Interactive Data Analysis*. Wiley.")
)
.tab_stubhead(label="landmass")
)
```
44 changes: 44 additions & 0 deletions tests/docs/typst/tables/great-tables/oceanea.qmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
---
title: "Great Tables - Oceanea"
format: typst
keep-md: true
format-links: false
---

```{python}
from great_tables import GT
from great_tables.data import countrypops
import polars as pl
import polars.selectors as cs
# Get vectors of 2-letter country codes for each region of Oceania
oceania = {
"Australasia": ["AU", "NZ"],
"Melanesia": ["NC", "PG", "SB", "VU"],
"Micronesia": ["FM", "GU", "KI", "MH", "MP", "NR", "PW"],
"Polynesia": ["PF", "WS", "TO", "TV"],
}
# Create a dictionary mapping country to region (e.g. AU -> Australasia)
country_to_region = {
country: region for region, countries in oceania.items() for country in countries
}
wide_pops = (
pl.from_pandas(countrypops)
.filter(
pl.col("country_code_2").is_in(list(country_to_region))
& pl.col("year").is_in([2000, 2010, 2020])
)
.with_columns(pl.col("country_code_2").replace(country_to_region).alias("region"))
.pivot(index=["country_name", "region"], columns="year", values="population")
.sort("2020", descending=True)
)
(
GT(wide_pops, rowname_col="country_name", groupname_col="region")
.tab_header(title="Populations of Oceania's Countries in 2000, 2010, and 2020")
.tab_spanner(label="Total Population", columns=cs.all())
.fmt_integer()
)
```
51 changes: 51 additions & 0 deletions tests/docs/typst/tables/gt/air-quality.qmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
---
title: "gt - Air Quality"
format: typst
keep-md: true
format-links: false
---

```{r}
library(gt)
library(dplyr)
# Modify the `airquality` dataset by adding the year
# of the measurements (1973) and limiting to 10 rows
airquality_m <-
airquality |>
mutate(Year = 1973L) |>
slice(1:10)
# Create a display table using the `airquality`
# dataset; arrange columns into groups
gt_tbl <-
gt(airquality_m) |>
tab_header(
title = "New York Air Quality Measurements",
subtitle = "Daily measurements in New York City (May 1-10, 1973)"
) |>
tab_spanner(
label = "Time",
columns = c(Year, Month, Day)
) |>
tab_spanner(
label = "Measurement",
columns = c(Ozone, Solar.R, Wind, Temp)
)
gt_tbl <-
gt_tbl |>
cols_move_to_start(
columns = c(Year, Month, Day)
) |>
cols_label(
Ozone = html("Ozone,<br>ppbV"),
Solar.R = html("Solar R.,<br>cal/m<sup>2</sup>"),
Wind = html("Wind,<br>mph"),
Temp = html("Temp,<br>&deg;F")
)
# Show the gt table
gt_tbl
```
41 changes: 41 additions & 0 deletions tests/docs/typst/tables/gt/islands.qmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
---
title: "gt - Islands"
format: typst
keep-md: true
format-links: false
---

```{r}
library(gt)
library(dplyr)
islands_tbl <-
tibble(
name = names(islands),
size = islands
) |>
arrange(desc(size)) |>
slice(1:10)
gt_tbl <- gt(islands_tbl)
gt_tbl <-
gt_tbl |>
tab_header(
title = "Large Landmasses of the World",
subtitle = "The top ten largest are presented"
)
gt_tbl <-
gt_tbl |>
tab_source_note(
source_note = "Source: The World Almanac and Book of Facts, 1975, page 406."
) |>
tab_source_note(
source_note = md("Reference: McNeil, D. R. (1977) *Interactive Data Analysis*. Wiley.")
)
# Show the gt table
gt_tbl
```
54 changes: 54 additions & 0 deletions tests/docs/typst/tables/gt/mtcars.qmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
---
title: "gt - mtcars"
format: typst
keep-typ: true
keep-md: true
format-links: false
---

```{=typst}
// this example is a little large for a standard page, at least at 0.75px = 1pt
// and we don't have
#set page(margin: 0cm)
// striped
// #set table(fill: (_,y) => if calc.odd(y) {luma(240)} else {white})
```


```{r}
library(dplyr)
library(gt)
gtcars_8 <-
gtcars |>
group_by(ctry_origin) |>
slice_head(n = 2) |>
ungroup() |>
filter(ctry_origin != "United Kingdom")
# Define our preferred order for `ctry_origin`
order_countries <- c("Germany", "Italy", "United States", "Japan")
```


```{r}
# Reorder the table rows by our specific ordering of groups
tab <-
gtcars_8 |>
arrange(
factor(ctry_origin, levels = order_countries),
mfr, desc(msrp)
) |>
mutate(car = paste(mfr, model)) |>
select(-mfr, -model) |>
group_by(ctry_origin) |>
gt(rowname_col = "car")
# Show the table
tab
```
24 changes: 24 additions & 0 deletions tests/docs/typst/tables/gt/test-pattern.qmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
---
title: "gt - Test Pattern"
format: typst
keep-typ: true
keep-md: true
format-links: false
filters:
- typst-annotate.lua
---

```{=typst}
#set page(margin: 0.5cm)
```

```{r}
library(dplyr)
library(gt)
exibble |>
gt() |>
data_color()
```
28 changes: 28 additions & 0 deletions tests/docs/typst/tables/pandas/acting-on-data.qmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
---
title: "Pandas - Acting on Data"
format: typst
keep-md: true
format-links: false
---

```{python}
import pandas as pd
import numpy as np
np.random.seed(0)
df2 = pd.DataFrame(np.random.randn(10,4), columns=['A','B','C','D'])
def style_negative(v, props=''):
return props if v < 0 else None
s2 = df2.style.map(style_negative, props='color:red;')\
.map(lambda v: 'opacity: 20%;' if (v < 0.3) and (v > -0.3) else None)
def highlight_max(s, props=''):
return np.where(s == np.nanmax(s.values), props, '')
# darkblue, pink
s2.apply(highlight_max, props='color:white;background-color:#00008b', axis=0)\
.apply(highlight_max, props='color:white;background-color: #ffc0cb;', axis=1)\
.apply(highlight_max, props='color:white;background-color:purple', axis=None)
```
18 changes: 18 additions & 0 deletions tests/docs/typst/tables/pandas/concatenating-stylers.qmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
title: "Concatenating Stylers"
format: typst
keep-md: true
format-links: false
---

```{python}
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(5, 5))
summary_styler = df.agg(["sum", "mean"]).style \
.format(precision=3) \
.relabel_index(["Sum", "Average"])
df.style.format(precision=1).concat(summary_styler)
```
51 changes: 51 additions & 0 deletions tests/docs/typst/tables/pandas/data-cell-css-classes.qmd
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
---
title: "Pandas - Data Cell CSS Classes"
format: typst
keep-md: true
format-links: false
---

```{python}
import pandas as pd
import numpy as np
df = pd.DataFrame([[38.0, 2.0, 18.0, 22.0, 21, np.nan],[19, 439, 6, 452, 226,232]],
index=pd.Index(['Tumour (Positive)', 'Non-Tumour (Negative)'], name='Actual Label:'),
columns=pd.MultiIndex.from_product([['Decision Tree', 'Regression', 'Random'],['Tumour', 'Non-Tumour']], names=['Model:', 'Predicted:']))
s = df.style.format('{:.0f}').hide([('Random', 'Tumour'), ('Random', 'Non-Tumour')], axis="columns")
cell_hover = { # for row hover use <tr> instead of <td>
'selector': 'td:hover',
'props': [('background-color', '#ffffb3')]
}
index_names = {
'selector': '.index_name',
# darkgr[ae]y
'props': 'font-style: italic; color: #a9a9a9; font-weight:normal;'
}
headers = {
'selector': 'th:not(.index_name)',
'props': 'background-color: #000066; color: white;'
}
s.set_table_styles([cell_hover, index_names, headers])
s.set_table_styles([ # create internal CSS classes
{'selector': '.true', 'props': 'background-color: #e6ffe6;'},
{'selector': '.false', 'props': 'background-color: #ffe6e6;'},
], overwrite=False)
cell_color = pd.DataFrame([['true ', 'false ', 'true ', 'false '],
['false ', 'true ', 'false ', 'true ']],
index=df.index,
columns=df.columns[:4])
s.set_td_classes(cell_color)
s.set_table_styles([ # create internal CSS classes
{'selector': '.border-red', 'props': 'border: 2px dashed red;'},
{'selector': '.border-green', 'props': 'border: 2px dashed green;'},
], overwrite=False)
cell_border = pd.DataFrame([['border-green ', ' ', ' ', 'border-red '],
[' ', ' ', ' ', ' ']],
index=df.index,
columns=df.columns[:4])
s.set_td_classes(cell_color + cell_border)
```

0 comments on commit d415ca1

Please sign in to comment.