001 /* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
006 *
007 * Project Info: http://www.jfree.org/jfreechart/index.html
008 *
009 * This library is free software; you can redistribute it and/or modify it
010 * under the terms of the GNU Lesser General Public License as published by
011 * the Free Software Foundation; either version 2.1 of the License, or
012 * (at your option) any later version.
013 *
014 * This library is distributed in the hope that it will be useful, but
015 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
016 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
017 * License for more details.
018 *
019 * You should have received a copy of the GNU Lesser General Public
020 * License along with this library; if not, write to the Free Software
021 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
022 * USA.
023 *
024 * [Java is a trademark or registered trademark of Sun Microsystems, Inc.
025 * in the United States and other countries.]
026 *
027 * ------------------------
028 * StackedAreaRenderer.java
029 * ------------------------
030 * (C) Copyright 2002-2008, by Dan Rivett (d.rivett@ukonline.co.uk) and
031 * Contributors.
032 *
033 * Original Author: Dan Rivett (adapted from AreaCategoryItemRenderer);
034 * Contributor(s): Jon Iles;
035 * David Gilbert (for Object Refinery Limited);
036 * Christian W. Zuckschwerdt;
037 *
038 * Changes:
039 * --------
040 * 20-Sep-2002 : Version 1, contributed by Dan Rivett;
041 * 24-Oct-2002 : Amendments for changes in CategoryDataset interface and
042 * CategoryToolTipGenerator interface (DG);
043 * 01-Nov-2002 : Added tooltips (DG);
044 * 06-Nov-2002 : Renamed drawCategoryItem() --> drawItem() and now using axis
045 * for category spacing. Renamed StackedAreaCategoryItemRenderer
046 * --> StackedAreaRenderer (DG);
047 * 26-Nov-2002 : Switched CategoryDataset --> TableDataset (DG);
048 * 26-Nov-2002 : Replaced isStacked() method with getRangeType() method (DG);
049 * 17-Jan-2003 : Moved plot classes to a separate package (DG);
050 * 25-Mar-2003 : Implemented Serializable (DG);
051 * 13-May-2003 : Modified to take into account the plot orientation (DG);
052 * 30-Jul-2003 : Modified entity constructor (CZ);
053 * 07-Oct-2003 : Added renderer state (DG);
054 * 29-Apr-2004 : Added getRangeExtent() override (DG);
055 * 05-Nov-2004 : Modified drawItem() signature (DG);
056 * 07-Jan-2005 : Renamed getRangeExtent() --> findRangeBounds() (DG);
057 * ------------- JFREECHART 1.0.x ---------------------------------------------
058 * 11-Oct-2006 : Added support for rendering data values as percentages,
059 * and added a second pass for drawing item labels (DG);
060 *
061 */
062
063 package org.jfree.chart.renderer.category;
064
065 import java.awt.Graphics2D;
066 import java.awt.Paint;
067 import java.awt.Shape;
068 import java.awt.geom.GeneralPath;
069 import java.awt.geom.Rectangle2D;
070 import java.io.Serializable;
071
072 import org.jfree.chart.axis.CategoryAxis;
073 import org.jfree.chart.axis.ValueAxis;
074 import org.jfree.chart.entity.EntityCollection;
075 import org.jfree.chart.event.RendererChangeEvent;
076 import org.jfree.chart.plot.CategoryPlot;
077 import org.jfree.data.DataUtilities;
078 import org.jfree.data.Range;
079 import org.jfree.data.category.CategoryDataset;
080 import org.jfree.data.general.DatasetUtilities;
081 import org.jfree.ui.RectangleEdge;
082 import org.jfree.util.PublicCloneable;
083
084 /**
085 * A renderer that draws stacked area charts for a {@link CategoryPlot}.
086 * The example shown here is generated by the
087 * <code>StackedAreaChartDemo1.java</code> program included in the
088 * JFreeChart Demo Collection:
089 * <br><br>
090 * <img src="../../../../../images/StackedAreaRendererSample.png"
091 * alt="StackedAreaRendererSample.png" />
092 */
093 public class StackedAreaRenderer extends AreaRenderer
094 implements Cloneable, PublicCloneable, Serializable {
095
096 /** For serialization. */
097 private static final long serialVersionUID = -3595635038460823663L;
098
099 /** A flag that controls whether the areas display values or percentages. */
100 private boolean renderAsPercentages;
101
102 /**
103 * Creates a new renderer.
104 */
105 public StackedAreaRenderer() {
106 this(false);
107 }
108
109 /**
110 * Creates a new renderer.
111 *
112 * @param renderAsPercentages a flag that controls whether the data values
113 * are rendered as percentages.
114 */
115 public StackedAreaRenderer(boolean renderAsPercentages) {
116 super();
117 this.renderAsPercentages = renderAsPercentages;
118 }
119
120 /**
121 * Returns <code>true</code> if the renderer displays each item value as
122 * a percentage (so that the stacked areas add to 100%), and
123 * <code>false</code> otherwise.
124 *
125 * @return A boolean.
126 *
127 * @since 1.0.3
128 */
129 public boolean getRenderAsPercentages() {
130 return this.renderAsPercentages;
131 }
132
133 /**
134 * Sets the flag that controls whether the renderer displays each item
135 * value as a percentage (so that the stacked areas add to 100%), and sends
136 * a {@link RendererChangeEvent} to all registered listeners.
137 *
138 * @param asPercentages the flag.
139 *
140 * @since 1.0.3
141 */
142 public void setRenderAsPercentages(boolean asPercentages) {
143 this.renderAsPercentages = asPercentages;
144 fireChangeEvent();
145 }
146
147 /**
148 * Returns the number of passes (<code>2</code>) required by this renderer.
149 * The first pass is used to draw the bars, the second pass is used to
150 * draw the item labels (if visible).
151 *
152 * @return The number of passes required by the renderer.
153 */
154 public int getPassCount() {
155 return 2;
156 }
157
158 /**
159 * Returns the range of values the renderer requires to display all the
160 * items from the specified dataset.
161 *
162 * @param dataset the dataset (<code>null</code> not permitted).
163 *
164 * @return The range (or <code>null</code> if the dataset is empty).
165 */
166 public Range findRangeBounds(CategoryDataset dataset) {
167 if (this.renderAsPercentages) {
168 return new Range(0.0, 1.0);
169 }
170 else {
171 return DatasetUtilities.findStackedRangeBounds(dataset);
172 }
173 }
174
175 /**
176 * Draw a single data item.
177 *
178 * @param g2 the graphics device.
179 * @param state the renderer state.
180 * @param dataArea the data plot area.
181 * @param plot the plot.
182 * @param domainAxis the domain axis.
183 * @param rangeAxis the range axis.
184 * @param dataset the data.
185 * @param row the row index (zero-based).
186 * @param column the column index (zero-based).
187 * @param pass the pass index.
188 */
189 public void drawItem(Graphics2D g2,
190 CategoryItemRendererState state,
191 Rectangle2D dataArea,
192 CategoryPlot plot,
193 CategoryAxis domainAxis,
194 ValueAxis rangeAxis,
195 CategoryDataset dataset,
196 int row,
197 int column,
198 int pass) {
199
200 // setup for collecting optional entity info...
201 Shape entityArea = null;
202 EntityCollection entities = state.getEntityCollection();
203
204 double y1 = 0.0;
205 Number n = dataset.getValue(row, column);
206 if (n != null) {
207 y1 = n.doubleValue();
208 }
209 double[] stack1 = getStackValues(dataset, row, column);
210
211
212 // leave the y values (y1, y0) untranslated as it is going to be be
213 // stacked up later by previous series values, after this it will be
214 // translated.
215 double xx1 = domainAxis.getCategoryMiddle(column, getColumnCount(),
216 dataArea, plot.getDomainAxisEdge());
217
218
219 // get the previous point and the next point so we can calculate a
220 // "hot spot" for the area (used by the chart entity)...
221 double y0 = 0.0;
222 n = dataset.getValue(row, Math.max(column - 1, 0));
223 if (n != null) {
224 y0 = n.doubleValue();
225 }
226 double[] stack0 = getStackValues(dataset, row, Math.max(column - 1, 0));
227
228 // FIXME: calculate xx0
229 double xx0 = domainAxis.getCategoryStart(column, getColumnCount(),
230 dataArea, plot.getDomainAxisEdge());
231
232 int itemCount = dataset.getColumnCount();
233 double y2 = 0.0;
234 n = dataset.getValue(row, Math.min(column + 1, itemCount - 1));
235 if (n != null) {
236 y2 = n.doubleValue();
237 }
238 double[] stack2 = getStackValues(dataset, row, Math.min(column + 1,
239 itemCount - 1));
240
241 double xx2 = domainAxis.getCategoryEnd(column, getColumnCount(),
242 dataArea, plot.getDomainAxisEdge());
243
244 // FIXME: calculate xxLeft and xxRight
245 double xxLeft = xx0;
246 double xxRight = xx2;
247
248 double[] stackLeft = averageStackValues(stack0, stack1);
249 double[] stackRight = averageStackValues(stack1, stack2);
250 double[] adjStackLeft = adjustedStackValues(stack0, stack1);
251 double[] adjStackRight = adjustedStackValues(stack1, stack2);
252
253 float transY1;
254
255 RectangleEdge edge1 = plot.getRangeAxisEdge();
256
257 GeneralPath left = new GeneralPath();
258 GeneralPath right = new GeneralPath();
259 if (y1 >= 0.0) { // handle positive value
260 transY1 = (float) rangeAxis.valueToJava2D(y1 + stack1[1], dataArea,
261 edge1);
262 float transStack1 = (float) rangeAxis.valueToJava2D(stack1[1],
263 dataArea, edge1);
264 float transStackLeft = (float) rangeAxis.valueToJava2D(
265 adjStackLeft[1], dataArea, edge1);
266
267 // LEFT POLYGON
268 if (y0 >= 0.0) {
269 double yleft = (y0 + y1) / 2.0 + stackLeft[1];
270 float transYLeft
271 = (float) rangeAxis.valueToJava2D(yleft, dataArea, edge1);
272 left.moveTo((float) xx1, transY1);
273 left.lineTo((float) xx1, transStack1);
274 left.lineTo((float) xxLeft, transStackLeft);
275 left.lineTo((float) xxLeft, transYLeft);
276 left.closePath();
277 }
278 else {
279 left.moveTo((float) xx1, transStack1);
280 left.lineTo((float) xx1, transY1);
281 left.lineTo((float) xxLeft, transStackLeft);
282 left.closePath();
283 }
284
285 float transStackRight = (float) rangeAxis.valueToJava2D(
286 adjStackRight[1], dataArea, edge1);
287 // RIGHT POLYGON
288 if (y2 >= 0.0) {
289 double yright = (y1 + y2) / 2.0 + stackRight[1];
290 float transYRight
291 = (float) rangeAxis.valueToJava2D(yright, dataArea, edge1);
292 right.moveTo((float) xx1, transStack1);
293 right.lineTo((float) xx1, transY1);
294 right.lineTo((float) xxRight, transYRight);
295 right.lineTo((float) xxRight, transStackRight);
296 right.closePath();
297 }
298 else {
299 right.moveTo((float) xx1, transStack1);
300 right.lineTo((float) xx1, transY1);
301 right.lineTo((float) xxRight, transStackRight);
302 right.closePath();
303 }
304 }
305 else { // handle negative value
306 transY1 = (float) rangeAxis.valueToJava2D(y1 + stack1[0], dataArea,
307 edge1);
308 float transStack1 = (float) rangeAxis.valueToJava2D(stack1[0],
309 dataArea, edge1);
310 float transStackLeft = (float) rangeAxis.valueToJava2D(
311 adjStackLeft[0], dataArea, edge1);
312
313 // LEFT POLYGON
314 if (y0 >= 0.0) {
315 left.moveTo((float) xx1, transStack1);
316 left.lineTo((float) xx1, transY1);
317 left.lineTo((float) xxLeft, transStackLeft);
318 left.clone();
319 }
320 else {
321 double yleft = (y0 + y1) / 2.0 + stackLeft[0];
322 float transYLeft = (float) rangeAxis.valueToJava2D(yleft,
323 dataArea, edge1);
324 left.moveTo((float) xx1, transY1);
325 left.lineTo((float) xx1, transStack1);
326 left.lineTo((float) xxLeft, transStackLeft);
327 left.lineTo((float) xxLeft, transYLeft);
328 left.closePath();
329 }
330 float transStackRight = (float) rangeAxis.valueToJava2D(
331 adjStackRight[0], dataArea, edge1);
332
333 // RIGHT POLYGON
334 if (y2 >= 0.0) {
335 right.moveTo((float) xx1, transStack1);
336 right.lineTo((float) xx1, transY1);
337 right.lineTo((float) xxRight, transStackRight);
338 right.closePath();
339 }
340 else {
341 double yright = (y1 + y2) / 2.0 + stackRight[0];
342 float transYRight = (float) rangeAxis.valueToJava2D(yright,
343 dataArea, edge1);
344 right.moveTo((float) xx1, transStack1);
345 right.lineTo((float) xx1, transY1);
346 right.lineTo((float) xxRight, transYRight);
347 right.lineTo((float) xxRight, transStackRight);
348 right.closePath();
349 }
350 }
351
352 g2.setPaint(getItemPaint(row, column));
353 g2.setStroke(getItemStroke(row, column));
354
355 // Get series Paint and Stroke
356 Paint itemPaint = getItemPaint(row, column);
357 if (pass == 0) {
358 g2.setPaint(itemPaint);
359 g2.fill(left);
360 g2.fill(right);
361 }
362
363 // add an entity for the item...
364 if (entities != null) {
365 GeneralPath gp = new GeneralPath(left);
366 gp.append(right, false);
367 entityArea = gp;
368 addItemEntity(entities, dataset, row, column, entityArea);
369 }
370
371 }
372
373 /**
374 * Calculates the stacked value of the all series up to, but not including
375 * <code>series</code> for the specified category, <code>category</code>.
376 * It returns 0.0 if <code>series</code> is the first series, i.e. 0.
377 *
378 * @param dataset the dataset (<code>null</code> not permitted).
379 * @param series the series.
380 * @param category the category.
381 *
382 * @return double returns a cumulative value for all series' values up to
383 * but excluding <code>series</code> for Object
384 * <code>category</code>.
385 */
386 protected double getPreviousHeight(CategoryDataset dataset,
387 int series, int category) {
388
389 double result = 0.0;
390 Number n;
391 double total = 0.0;
392 if (this.renderAsPercentages) {
393 total = DataUtilities.calculateColumnTotal(dataset, category);
394 }
395 for (int i = 0; i < series; i++) {
396 n = dataset.getValue(i, category);
397 if (n != null) {
398 double v = n.doubleValue();
399 if (this.renderAsPercentages) {
400 v = v / total;
401 }
402 result += v;
403 }
404 }
405 return result;
406
407 }
408
409 /**
410 * Calculates the stacked values (one positive and one negative) of all
411 * series up to, but not including, <code>series</code> for the specified
412 * item. It returns [0.0, 0.0] if <code>series</code> is the first series.
413 *
414 * @param dataset the dataset (<code>null</code> not permitted).
415 * @param series the series index.
416 * @param index the item index.
417 *
418 * @return An array containing the cumulative negative and positive values
419 * for all series values up to but excluding <code>series</code>
420 * for <code>index</code>.
421 */
422 protected double[] getStackValues(CategoryDataset dataset,
423 int series, int index) {
424 double[] result = new double[2];
425 for (int i = 0; i < series; i++) {
426 if (isSeriesVisible(i)) {
427 double v = 0.0;
428 Number n = dataset.getValue(i, index);
429 if (n != null) {
430 v = n.doubleValue();
431 }
432 if (!Double.isNaN(v)) {
433 if (v >= 0.0) {
434 result[1] += v;
435 }
436 else {
437 result[0] += v;
438 }
439 }
440 }
441 }
442 return result;
443 }
444
445 /**
446 * Returns a pair of "stack" values calculated as the mean of the two
447 * specified stack value pairs.
448 *
449 * @param stack1 the first stack pair.
450 * @param stack2 the second stack pair.
451 *
452 * @return A pair of average stack values.
453 */
454 private double[] averageStackValues(double[] stack1, double[] stack2) {
455 double[] result = new double[2];
456 result[0] = (stack1[0] + stack2[0]) / 2.0;
457 result[1] = (stack1[1] + stack2[1]) / 2.0;
458 return result;
459 }
460
461 /**
462 * Calculates adjusted stack values from the supplied values. The value is
463 * the mean of the supplied values, unless either of the supplied values
464 * is zero, in which case the adjusted value is zero also.
465 *
466 * @param stack1 the first stack pair.
467 * @param stack2 the second stack pair.
468 *
469 * @return A pair of average stack values.
470 */
471 private double[] adjustedStackValues(double[] stack1, double[] stack2) {
472 double[] result = new double[2];
473 if (stack1[0] == 0.0 || stack2[0] == 0.0) {
474 result[0] = 0.0;
475 }
476 else {
477 result[0] = (stack1[0] + stack2[0]) / 2.0;
478 }
479 if (stack1[1] == 0.0 || stack2[1] == 0.0) {
480 result[1] = 0.0;
481 }
482 else {
483 result[1] = (stack1[1] + stack2[1]) / 2.0;
484 }
485 return result;
486 }
487
488 /**
489 * Checks this instance for equality with an arbitrary object.
490 *
491 * @param obj the object (<code>null</code> not permitted).
492 *
493 * @return A boolean.
494 */
495 public boolean equals(Object obj) {
496 if (obj == this) {
497 return true;
498 }
499 if (!(obj instanceof StackedAreaRenderer)) {
500 return false;
501 }
502 StackedAreaRenderer that = (StackedAreaRenderer) obj;
503 if (this.renderAsPercentages != that.renderAsPercentages) {
504 return false;
505 }
506 return super.equals(obj);
507 }
508 }