Search code examples
javascriptjsondatatablessparklines

Using Sparkline bar charts in Datatables.net, can I highlight just one of the bars on the chart with a different color?


I present bar charts in datatables.net using the configuration suggested by @KevinDasilva at https://stackoverflow.com/a/51749815/12417398 ... What I need is to add a properly placed red bar to either this bar chart, or to add an under or overlapping second chart with one-bar in a different color - I can find no documentation on this.

The datatables.net table and chart looks as follows:

One-color Sparklines bar charts

Rather than use aocolumns, I leave this datatables config-line out and add text to the data directly in json - which looks like:

[{"Color":"2-Yellow","Indicator":"Export per Capita","TEP Chart":"<img src=\"Export.per.Capita.jpg\">","Chart":"<span class=\"spark\">0.  ,0.  ,0.25,0.19,0.25,0.31,0.19,0.5 ,0.44,0.67,0.67,0.87,1.  <\/span>"},{each line repeats ...}]

Any experience, suggestions, or working examples are greatly appreciated.

I am pleased to say this was answered with an hour and the two libraries work well together ... I hope it helps others because this is a very interesting tool with this addition.

Sparkline Chart with a second color exactly where required ...


Solution

  • This uses the jQuery Sparklines library.

    If you use a 2-element array for each data point, you can create a stacked bar chart. You can then set all of the values to zero for one value in each pair, so there are never any actual stacks.

    This lets you control the colors, as if you had painted specific bars a different color.

    Try this outside of DataTables, as a demo:

    <span class="bar1"></span>
    
    $('.bar1').sparkline([ [1,0], [2,0], [0,3], [4,0] ], { type: 'bar' });
    

    Note the [0,3] array, which will generate a red bar. All the other bars will be blue. These are the default colors:

    enter image description here

    You can specify custom colors:

    $('.bar1').sparkline([ [1,0], [2,0], [0,3], [4,0] ], 
        { type: 'bar', stackedBarColor: ['red', 'green'] });
    

    For additional features see the documentation here.

    Note:

    Stacked bar charts require version 2.0 or higher.