Applying color gradients to columns
Numeric trends in larger tables can quickly become difficult to see. Adding color to reveal these trends can be one way to make reading complex tables a little easier.
The data
Clean gradients in real data can be hard to come by. Excuse the contrived nature of the data below, but I really want to make a rainbow gradient!
julia
using StyledTables, DataFrames, Colors
df = DataFrame(id = 1:8, score = rand(8))8×2 DataFrame
| Row | id | score |
|---|---|---|
| Int64 | Float64 | |
| 1 | 1 | 0.0950849 |
| 2 | 2 | 0.853867 |
| 3 | 3 | 0.798711 |
| 4 | 4 | 0.189471 |
| 5 | 5 | 0.424149 |
| 6 | 6 | 0.40882 |
| 7 | 7 | 0.613054 |
| 8 | 8 | 0.828007 |
So far so boring.
The gradient we'll be applying is the following:
julia
colors = range(HSV(0,1,1), stop = HSV(-360,1,1), length = nrow(df))Step 1: Styling function
The function below is more general than what would be required for the specific example here. In our case, it would be possible to simply use the id variable to index into colors.
julia
function apply_gradient(x, xmax; colors)
color = colors[round(Int, (x / xmax) * length(colors))]
return (; color)
endapply_gradient (generic function with 1 method)Step 2: Apply styling
julia
tbl = StyledTable(df)
tab_style!(x -> apply_gradient(x, maximum(df.id); colors), tbl, :id)
render(tbl)| id | score |
| 1 | 0.0951 |
| 2 | 0.854 |
| 3 | 0.799 |
| 4 | 0.189 |
| 5 | 0.424 |
| 6 | 0.409 |
| 7 | 0.613 |
| 8 | 0.828 |
Step 3: Column labels
julia
cols_label!(tbl, :id => "Student ID", :score => "Score")
render(tbl)| Student ID | Score |
| 1 | 0.0951 |
| 2 | 0.854 |
| 3 | 0.799 |
| 4 | 0.189 |
| 5 | 0.424 |
| 6 | 0.409 |
| 7 | 0.613 |
| 8 | 0.828 |