Goibon
Goibon

Reputation: 251

How can I create a horizontal stacked bar chart with labels on the bars themselves as well as labels above the bars?

I'm trying to create a horizontal stacked bar chart with labels on the bars themselves (currently using dataLabels) as well as labels just above the bars. Here is a JSFiddle I've created that somewhat resembles what I am trying to accomplish. In this example I've placed the labels using plotLine labels, but I'm having a difficult time figuring out how to place the bars correctly in my real use case as I get the data for the bars through Ajax calls.

JSFiddle

I've experimented with stackLabels, plotLine labels as well as plotBand labels but to no avail. How can I place labels above the bars correctly every time?

Upvotes: 0

Views: 113

Answers (1)

jlbriggs
jlbriggs

Reputation: 17791

I would use plotBands instead of plotLines - you can better control the alignment within the band, which can be set to cover the same portion of the graph as the bar itself.

An example.

Using your series data:

var series = [{
    name: 'John',
    data: [5]
  },
  {
    name: 'Jane',
    data: [2]
  }, {
    name: 'Joe',
    data: [3]
  }]

We can loop through and build a plotBands array from the same data:

var bands = [],
    prevData = 0;

$.each(series, function(i,ser) {
    var point = ser.data[0],
            name = ser.name;
    bands.push({
        from: prevData,
        to: (prevData + point),
        color: 'rgba(255,255,255,0)',
        label: {
            text: name,
            align: 'center'
        }
    });
    prevData = (prevData+point);
});

To make this match the order of the series as plotted, we need to set reversedStacks: false on the yAxis, as by default, Highcharts reverses the order of the series. Then we populate the plotBands with our generated array:

yAxis: {
  reversedStacks: false,
  plotBands: bands
}

In this way you can make use of the full feature set of the plotBands label properties.

Updated fiddle:

And this adjusts to fit however many data points you have, provided you keep the same format (series.name, series.data[0]):

There are a number of other ways you can go about this as well, including:

Upvotes: 1

Related Questions