Chartjs-Change the color of the bar chart based on range value

1πŸ‘

βœ…

  1. Iterate each element in BarDataExample.SimpleBar array, and assign each element’s BackgroundColor and BorderColor values according to dataItem.Value.Value.

  2. Select the values of BackgroundColor and BorderColor from the BarDataExample.SimpleBar and assign them to the config for BackgroundColor and BorderColor of BarDataset instance respectively.

foreach (var dataItem in BarDataExample.SimpleBar)
{
    if (dataItem.Value.HasValue)
    {
        if (dataItem.Value.Value >= (decimal)0m
            && dataItem.Value.Value < (decimal)1.25m)
        {
            dataItem.BackgroundColor = "#008000";
            dataItem.BorderColor = "#008000";
        }
        else if (dataItem.Value.Value >= (decimal)1.25m
            && dataItem.Value.Value < (decimal)2.5m)
        {
            dataItem.BackgroundColor = "#FFA500";
            dataItem.BorderColor = "#FFA500";
        }
        else if (dataItem.Value.Value >= (decimal)2.5
            && dataItem.Value.Value < (decimal)3.75m)
        {
            dataItem.BackgroundColor = "#ff0000";
            dataItem.BorderColor = "#ff0000";
        }
        else if (dataItem.Value.Value >= (decimal)3.75m
            && dataItem.Value.Value < (decimal)5m)
        {
            dataItem.BackgroundColor = "#000000";
            dataItem.BorderColor = "#000000";
        }
        else
        {
            dataItem.BackgroundColor = "#D3D3D3";
            dataItem.BorderColor = "#D3D3D3";
        }
    }
}

_config1.Data.Datasets.Add(new BarDataset()
{
    Label = "Value",
    Data = BarDataExample.SimpleBar.Select(l => l.Value).ToList(),
    BackgroundColor = BarDataExample.SimpleBar.Select(l => l.BackgroundColor).ToList(),
    BorderColor = BarDataExample.SimpleBar.Select(l => l.BorderColor).ToList(),
    BorderWidth = 1
});

Demo

enter image description here

Leave a comment