Text color as function of non-numeric column value #617
dafriedman97
started this conversation in
General
Replies: 2 comments 5 replies
-
Also curious how I could make the background color (for a column or the entire row) depend on the value. Thanks! |
Beta Was this translation helpful? Give feedback.
0 replies
-
Here’s my approach: import polars as pl
from great_tables import GT, style, loc
df = pl.DataFrame(
{
"city": ["New York", "Boston", "Chicago", "Seattle"],
"region": ["east", "east", "central", "west"],
}
)
gt = GT(df)
color_map = (
pl.when(pl.col("region").eq(pl.lit("east")))
.then(pl.lit("green"))
.when(pl.col("region").eq(pl.lit("central")))
.then(pl.lit("blue"))
.when(pl.col("region").eq(pl.lit("west")))
.then(pl.lit("red"))
)
# Format the city name using its corresponding mapping color.
(gt.tab_style(style=style.text(color=color_map), locations=loc.body("city")))
# Format the background color using its mapping color by specifying a column (or multiple columns).
(gt.tab_style(style=style.fill(color=color_map), locations=loc.body("city")))
# Format the background color using its mapping color by specifying a column (or multiple columns)
# and/or a row (or multiple rows).
(gt.tab_style(style=style.fill(color=color_map), locations=loc.body("city", rows=[0, 2]))) Hope this helps! Reference: Basic Styling in Great Tables. |
Beta Was this translation helpful? Give feedback.
5 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have a DataFrame with a non-numeric column and I want to color text as a function of that column's values. I also have a specific color mapping in mind. So say I have the following table
and a color mapping like
{'east': 'green', 'central': 'blue', 'west': 'red'}
. How can I format the city name with its mapping color?Beta Was this translation helpful? Give feedback.
All reactions