Flot includes a plugin that allows you to create stacked charts. Stacked charts are especially useful when the data in your series is meant to add up to some total value, for example percentage data.
Using the same boilerplate that we wrote in the Creating basic charts recipe, we just need to include the stack
plugin, as shown in the following code:
...
<script src="jquery.js"></script>
<script src="jquery.flot.js"></script>
<script src="jquery.flot.stack.js"></script>
...
Using the stack
plugin is simply a matter of specifying the stack
option. Stacked charts work best with bar charts and area charts.
...
<script src="jquery.flot.stack.js"></script>
<script>
$('#sampleChart').plot(
[
{ color: 'orange',
data: [[0, 3], [1, 4], [2, 2]] },
{ color: 'lightblue',
data: [[0, 6], [1, 3], [2, 6]] },
{ color: 'darkred',
data: [[0, 1], [1, 3], [2, 2]] }
],
{
series: {
stack: true,
bars: {
show: true,
barWidth: 0.2, align: 'center'
}
}
}
);
</script>
...
The stack
plugin will draw a chart that stacks the first points of each series together into one composite bar and the second points of each series into another bar, and so on:
The stack
plugin takes the data you specify and readjusts it in such a way that the corresponding data points in the series are offset from each other. The stack
plugin assumes that the series are already ordered from bottom to top. In this case, the first series is yellow in the chart, the second is blue, and the last is red.
The stack
plugin is quite simple. It only has one option, stack, but it can be used in an alternate way to create multiple groups of stacks on the same chart.
The stack
plugin also has the ability to group series to separate stacks. This is done by specifying a unique key on the stack
option of each series. The key can be any unique number or string. We combine this option with Flot's align
option on bar charts in order to display the stacks side-by-side:
... $('#sampleChart').plot( [ { color: 'orange', data: [[0, 1], [1, 5], [2, 2]], stack: 0, bars: {align: 'left'} }, { color: 'lightblue', data: [[0, 9], [1, 5], [2, 8]], stack: 0, bars: {align: 'left'} }, { color: 'darkred', data: [[0, 3], [1, 8], [2, 6]], stack: 1, bars: {align: 'right'} }, { color: 'green', data: [[0, 7], [1, 2], [2, 4]], stack: 1, bars: {align: 'right'} } ], { series: { bars: { show: true, barWidth: 0.2 } } } ); ...
The stack
plugin now draws a chart where the light blue and orange series are grouped into stack 0
and the green and dark red series are grouped into stack 1
: