Correct Math() syntax for conditional cell style in an ag grid

Hi,

I am trying to set set the background colour of a call in ag grid bia the following loop
(rel_delta holds relative difference data and the shading is meant to reflect to relative distance iin increasing shades of red)

# Define conditional formatting based on bins
background_colors = interpolate_rgb(color_scale_in=sequential.Reds,
                                    n_bins=n_bins)
legend = []
cond_list = []
for i, background_color in enumerate(background_colors):
    min_bound = step_val * i
    max_bound = min_bound + step_val

    # Add positive and negative conditions in one loop
    cond_list.append({
        'condition':  f'Math.abs(params.data[\'rel_delta\']) > {min_bound} && Math.abs(params.data[\'rel_delta\']) <= {max_bound}',
        'backgroundColor': background_color
    })

The list will then be inserted at the ‘styleConditions’ key to trigger the styling for the relevant column. now I do not seem to get the Math.abs() syntax to work correctly.

If there was experience with using the Math() functions in the ag grid namespace via Python, any advice or hint towards the correct usage would be greatly appreciated.

Thank you in advance and have a great weekend (hopefully soon)

Hi @Robster and welcome to the Dash community :slightly_smiling_face:

It is possible to use Math in the condition. Try using

f'Math.abs(params.value)

or

f'Math.abs(params.data.rel_delta)

or if you have spaces or dots in the column name

f'Math.abs(params.data["rel_delta"])

Also, check the console for any error messages.

If you are still having an issue, it would be helpful to create a complete minimal example that we can run.

HI @AnnMarieW,

you are a star! Thank you so much for your fast reply. Your advice pointed me towards the syntax error I was making with regards to the style to be applied.
The correct and working loop reads:

# Define conditional formatting based on bins
background_colors = interpolate_rgb(color_scale_in=sequential.Reds,
                                    n_bins=n_bins)
legend = []
cond_list = []
for i, background_color in enumerate(background_colors):
    min_bound = step_val * i
    max_bound = min_bound + step_val

    # Add positive and negative conditions in one loop
    cond_list.append({
        'condition':  f'Math.abs(params.data[\'rel_delta\']) > {min_bound} && Math.abs(params.data[\'rel_delta\']) <= {max_bound}',
       "style": {'backgroundColor': background_color}
    })

Enjoy your weekend! :slight_smile:

1 Like