How do I color a julia DataFrame column for output in Jupyter notebook?

80 views Asked by At

How do I apply a function that highlights cells of a particular df column a given color on a julia DataFrame for output into a Jupyter notebook?

using DataFrames
using Crayons

crayon_red_light = Crayon(foreground = :white, background = :light_red)

# Tried this
highlight_max = PrettyTables.Highlighter((data, i, j) -> crayon_red_light)
PrettyTables.pretty_table(df, highlighters = (highlight_max,))

# And this
for (i, row) in enumerate(eachrow(output_df))
    PrettyTables.hl_cell(i, findfirst(isequal("intensity_color"), names(output_df)), crayon_red_light)
end
PrettyTables.pretty_table(output_df)
1

There are 1 answers

4
Dan Getz On

If the goal is to have the maximum of each row highlighted, rummaging around the PrettyTables docs, led me to the following code:

julia> using DataFrames, PrettyTables, Crayons

julia> crayon_red_light = Crayon(foreground = :white, background = :light_red);

julia> highlight_max = PrettyTables.Highlighter(
  (data, i, j) -> (data[i,j] == maximum(data[i,:])), 
  crayon_red_light);

julia> output_df = DataFrame(rand(4,4),:auto);

julia> PrettyTables.pretty_table(output_df; highlighters=highlight_max)
┌──────────┬──────────┬────────────┬──────────┐
│       x1 │       x2 │         x3 │       x4 │
│  Float64 │  Float64 │    Float64 │  Float64 │
├──────────┼──────────┼────────────┼──────────┤
│ 0.832342 │ 0.863113 │   0.221362 │   0.4671 │
│ 0.785022 │ 0.490397 │   0.998645 │ 0.513297 │
│ 0.629783 │ 0.821462 │ 0.00826195 │ 0.682221 │
│ 0.633541 │ 0.614559 │    0.44059 │ 0.379653 │
└──────────┴──────────┴────────────┴──────────┘

Well, the table as it in the answer doesn't show the appropriately colored bits, but they are colored... As a bonus, to enable showing which cells are highlighted, the following is a Formatter setup to surround maximum values in row with stars:

julia> format_max(df) = (v,i,j)->(j==columnindex(df, argmax(df[i,:])) ? "*$(round(v;digits=6))*" : v)
format_max (generic function with 1 method)

julia> PrettyTables.pretty_table(output_df; highlighters=highlight_max, formatters=format_max(output_df))
┌────────────┬────────────┬──────────┬──────────┐
│         x1 │         x2 │       x3 │       x4 │
│    Float64 │    Float64 │  Float64 │  Float64 │
├────────────┼────────────┼──────────┼──────────┤
│ *0.922994* │   0.850852 │ 0.460552 │ 0.141286 │
│ *0.408714* │    0.38931 │ 0.121324 │ 0.191002 │
│ *0.229459* │   0.151925 │ 0.117629 │ 0.114009 │
│  0.0487133 │ *0.900163* │ 0.691286 │ 0.786792 │
└────────────┴────────────┴──────────┴──────────┘