PHPlot Sample - Negative Stacked Bars
Editor's note: This page was originally written up on 2010-09-21. The change described here was implemented in PHPlot-5.2.0.
This sample shows a stacked bar plot with negative values. PHPlot-5.1.3 and earlier do not support this.
Reference: Discussion thread 2010-09-21
- The first bar has all positive segments. This is the only form that works with PHPlot 5.1.3 and earlier.
- The second bar has all negative segments. The bar is drawn downward.
- The third bar has mixed positive and negative segments (3, -2, 4, -1). This is not recommended, but it works. The first segment sets the bar direction, positive in this case. Segments are not drawn if they don't extend the stack height, but they still contribute to the overall total. The labels need some explaining. The first segment has value 3 and label 3. The second segment value is -2, making the total 3-2=1, but this segment is not drawn because it does not increase the bar stack height. The third segment value is 4, making the total 1+4=5. So the third segment (actually the second visible, but using the third data color) is drawn to height 5, but is labeled with its value, 4. The fourth segment value is -1, making the stack total 4, but again it isn't drawn because it doesn't extend the height. The overall data value label for the stack is 4, which is the final total, even though the stack height is 5.
- The fourth bar also has mixed positive and negative segments, but in this case the first segment is negative so the bar direction is down. The same explanation of labels applies here.
Note that you cannot determine the segment values from the graph labels when negative and positive values are mixed. The goal with these mixed stacks is to be mathematically correct, not necessarily useful.
The Plot:

The Code:
~~~~
:::php
<?php
require_once 'phplot.php';
$data = array(
array('All Pos', 1, 2, 3, 4),
array('All Neg', -4, -3, -5, -2),
array('Pos, Mixed', 3, -2, 4, -1),
array('Neg, Mixed', -3, 2, -4, 1),
);
$p = new PHPlot(600, 450);
$p->SetTitle('Stacked Bars Extension - Negative Values');
$p->SetDataType('text-data');
$p->SetDataValues($data);
$p->SetPlotType('stackedbars');
$p->SetPlotAreaWorld(0, -15, 4, 15);
$p->SetYDataLabelPos('plotstack');
$p->SetXTickPos('none');
$p->DrawGraph();
~~~~~