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 * StackedBarRenderer.java
029 * -----------------------
030 * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
031 *
032 * Original Author: David Gilbert (for Object Refinery Limited);
033 * Contributor(s): Richard Atkinson;
034 * Thierry Saura;
035 * Christian W. Zuckschwerdt;
036 *
037 * Changes
038 * -------
039 * 19-Oct-2001 : Version 1 (DG);
040 * 22-Oct-2001 : Renamed DataSource.java --> Dataset.java etc. (DG);
041 * 23-Oct-2001 : Changed intro and trail gaps on bar plots to use percentage of
042 * available space rather than a fixed number of units (DG);
043 * 15-Nov-2001 : Modified to allow for null data values (DG);
044 * 22-Nov-2001 : Modified to allow for negative data values (DG);
045 * 13-Dec-2001 : Added tooltips (DG);
046 * 16-Jan-2002 : Fixed bug for single category datasets (DG);
047 * 15-Feb-2002 : Added isStacked() method (DG);
048 * 14-Mar-2002 : Modified to implement the CategoryItemRenderer interface (DG);
049 * 24-May-2002 : Incorporated tooltips into chart entities (DG);
050 * 11-Jun-2002 : Added check for (permitted) null info object, bug and fix
051 * reported by David Basten. Also updated Javadocs. (DG);
052 * 25-Jun-2002 : Removed redundant import (DG);
053 * 26-Jun-2002 : Small change to entity (DG);
054 * 05-Aug-2002 : Small modification to drawCategoryItem method to support URLs
055 * for HTML image maps (RA);
056 * 08-Aug-2002 : Added optional linking lines, contributed by Thierry
057 * Saura (DG);
058 * 26-Sep-2002 : Fixed errors reported by Checkstyle (DG);
059 * 24-Oct-2002 : Amendments for changes in CategoryDataset interface and
060 * CategoryToolTipGenerator interface (DG);
061 * 05-Nov-2002 : Replaced references to CategoryDataset with TableDataset (DG);
062 * 26-Nov-2002 : Replaced isStacked() method with getRangeType() method (DG);
063 * 17-Jan-2003 : Moved plot classes to a separate package (DG);
064 * 25-Mar-2003 : Implemented Serializable (DG);
065 * 12-May-2003 : Merged horizontal and vertical stacked bar renderers (DG);
066 * 30-Jul-2003 : Modified entity constructor (CZ);
067 * 08-Sep-2003 : Fixed bug 799668 (isBarOutlineDrawn() ignored) (DG);
068 * 16-Sep-2003 : Changed ChartRenderingInfo --> PlotRenderingInfo (DG);
069 * 21-Oct-2003 : Moved bar width into renderer state (DG);
070 * 26-Nov-2003 : Added code to respect maxBarWidth attribute (DG);
071 * 05-Nov-2004 : Changed to a two-pass renderer so that item labels are not
072 * overwritten by other bars (DG);
073 * 07-Jan-2005 : Renamed getRangeExtent() --> findRangeBounds() (DG);
074 * 29-Mar-2005 : Modified drawItem() method so that a zero value is handled
075 * within the code for positive rather than negative values (DG);
076 * 20-Apr-2005 : Renamed CategoryLabelGenerator
077 * --> CategoryItemLabelGenerator (DG);
078 * 17-May-2005 : Added flag to allow rendering values as percentages - inspired
079 * by patch 1200886 submitted by John Xiao (DG);
080 * 09-Jun-2005 : Added accessor methods for the renderAsPercentages flag,
081 * provided equals() method, and use addItemEntity from
082 * superclass (DG);
083 * 09-Jun-2005 : Added support for GradientPaint - see bug report 1215670 (DG);
084 * 22-Sep-2005 : Renamed getMaxBarWidth() --> getMaximumBarWidth() (DG);
085 * 29-Sep-2005 : Use outline stroke in drawItem method - see bug report
086 * 1304139 (DG);
087 * ------------- JFREECHART 1.0.x ---------------------------------------------
088 * 11-Oct-2006 : Source reformatting (DG);
089 * 24-Jun-2008 : Added new barPainter mechanism (DG);
090 *
091 */
092
093 package org.jfree.chart.renderer.category;
094
095 import java.awt.Graphics2D;
096 import java.awt.geom.Rectangle2D;
097 import java.io.Serializable;
098
099 import org.jfree.chart.axis.CategoryAxis;
100 import org.jfree.chart.axis.ValueAxis;
101 import org.jfree.chart.entity.EntityCollection;
102 import org.jfree.chart.event.RendererChangeEvent;
103 import org.jfree.chart.labels.CategoryItemLabelGenerator;
104 import org.jfree.chart.labels.ItemLabelAnchor;
105 import org.jfree.chart.labels.ItemLabelPosition;
106 import org.jfree.chart.plot.CategoryPlot;
107 import org.jfree.chart.plot.PlotOrientation;
108 import org.jfree.data.DataUtilities;
109 import org.jfree.data.Range;
110 import org.jfree.data.category.CategoryDataset;
111 import org.jfree.data.general.DatasetUtilities;
112 import org.jfree.ui.RectangleEdge;
113 import org.jfree.ui.TextAnchor;
114 import org.jfree.util.PublicCloneable;
115
116 /**
117 * A stacked bar renderer for use with the {@link CategoryPlot} class.
118 * The example shown here is generated by the
119 * <code>StackedBarChartDemo1.java</code> program included in the
120 * JFreeChart Demo Collection:
121 * <br><br>
122 * <img src="../../../../../images/StackedBarRendererSample.png"
123 * alt="StackedBarRendererSample.png" />
124 */
125 public class StackedBarRenderer extends BarRenderer
126 implements Cloneable, PublicCloneable, Serializable {
127
128 /** For serialization. */
129 static final long serialVersionUID = 6402943811500067531L;
130
131 /** A flag that controls whether the bars display values or percentages. */
132 private boolean renderAsPercentages;
133
134 /**
135 * Creates a new renderer. By default, the renderer has no tool tip
136 * generator and no URL generator. These defaults have been chosen to
137 * minimise the processing required to generate a default chart. If you
138 * require tool tips or URLs, then you can easily add the required
139 * generators.
140 */
141 public StackedBarRenderer() {
142 this(false);
143 }
144
145 /**
146 * Creates a new renderer.
147 *
148 * @param renderAsPercentages a flag that controls whether the data values
149 * are rendered as percentages.
150 */
151 public StackedBarRenderer(boolean renderAsPercentages) {
152 super();
153 this.renderAsPercentages = renderAsPercentages;
154
155 // set the default item label positions, which will only be used if
156 // the user requests visible item labels...
157 ItemLabelPosition p = new ItemLabelPosition(ItemLabelAnchor.CENTER,
158 TextAnchor.CENTER);
159 setBasePositiveItemLabelPosition(p);
160 setBaseNegativeItemLabelPosition(p);
161 setPositiveItemLabelPositionFallback(null);
162 setNegativeItemLabelPositionFallback(null);
163 }
164
165 /**
166 * Returns <code>true</code> if the renderer displays each item value as
167 * a percentage (so that the stacked bars add to 100%), and
168 * <code>false</code> otherwise.
169 *
170 * @return A boolean.
171 *
172 * @see #setRenderAsPercentages(boolean)
173 */
174 public boolean getRenderAsPercentages() {
175 return this.renderAsPercentages;
176 }
177
178 /**
179 * Sets the flag that controls whether the renderer displays each item
180 * value as a percentage (so that the stacked bars add to 100%), and sends
181 * a {@link RendererChangeEvent} to all registered listeners.
182 *
183 * @param asPercentages the flag.
184 *
185 * @see #getRenderAsPercentages()
186 */
187 public void setRenderAsPercentages(boolean asPercentages) {
188 this.renderAsPercentages = asPercentages;
189 fireChangeEvent();
190 }
191
192 /**
193 * Returns the number of passes (<code>3</code>) required by this renderer.
194 * The first pass is used to draw the bar shadows, the second pass is used
195 * to draw the bars, and the third pass is used to draw the item labels
196 * (if visible).
197 *
198 * @return The number of passes required by the renderer.
199 */
200 public int getPassCount() {
201 return 3;
202 }
203
204 /**
205 * Returns the range of values the renderer requires to display all the
206 * items from the specified dataset.
207 *
208 * @param dataset the dataset (<code>null</code> permitted).
209 *
210 * @return The range (or <code>null</code> if the dataset is empty).
211 */
212 public Range findRangeBounds(CategoryDataset dataset) {
213 if (dataset == null) {
214 return null;
215 }
216 if (this.renderAsPercentages) {
217 return new Range(0.0, 1.0);
218 }
219 else {
220 return DatasetUtilities.findStackedRangeBounds(dataset, getBase());
221 }
222 }
223
224 /**
225 * Calculates the bar width and stores it in the renderer state.
226 *
227 * @param plot the plot.
228 * @param dataArea the data area.
229 * @param rendererIndex the renderer index.
230 * @param state the renderer state.
231 */
232 protected void calculateBarWidth(CategoryPlot plot,
233 Rectangle2D dataArea,
234 int rendererIndex,
235 CategoryItemRendererState state) {
236
237 // calculate the bar width
238 CategoryAxis xAxis = plot.getDomainAxisForDataset(rendererIndex);
239 CategoryDataset data = plot.getDataset(rendererIndex);
240 if (data != null) {
241 PlotOrientation orientation = plot.getOrientation();
242 double space = 0.0;
243 if (orientation == PlotOrientation.HORIZONTAL) {
244 space = dataArea.getHeight();
245 }
246 else if (orientation == PlotOrientation.VERTICAL) {
247 space = dataArea.getWidth();
248 }
249 double maxWidth = space * getMaximumBarWidth();
250 int columns = data.getColumnCount();
251 double categoryMargin = 0.0;
252 if (columns > 1) {
253 categoryMargin = xAxis.getCategoryMargin();
254 }
255
256 double used = space * (1 - xAxis.getLowerMargin()
257 - xAxis.getUpperMargin()
258 - categoryMargin);
259 if (columns > 0) {
260 state.setBarWidth(Math.min(used / columns, maxWidth));
261 }
262 else {
263 state.setBarWidth(Math.min(used, maxWidth));
264 }
265 }
266
267 }
268
269 /**
270 * Draws a stacked bar for a specific item.
271 *
272 * @param g2 the graphics device.
273 * @param state the renderer state.
274 * @param dataArea the plot area.
275 * @param plot the plot.
276 * @param domainAxis the domain (category) axis.
277 * @param rangeAxis the range (value) axis.
278 * @param dataset the data.
279 * @param row the row index (zero-based).
280 * @param column the column index (zero-based).
281 * @param pass the pass index.
282 */
283 public void drawItem(Graphics2D g2,
284 CategoryItemRendererState state,
285 Rectangle2D dataArea,
286 CategoryPlot plot,
287 CategoryAxis domainAxis,
288 ValueAxis rangeAxis,
289 CategoryDataset dataset,
290 int row,
291 int column,
292 int pass) {
293
294 // nothing is drawn for null values...
295 Number dataValue = dataset.getValue(row, column);
296 if (dataValue == null) {
297 return;
298 }
299
300 double value = dataValue.doubleValue();
301 double total = 0.0; // only needed if calculating percentages
302 if (this.renderAsPercentages) {
303 total = DataUtilities.calculateColumnTotal(dataset, column);
304 value = value / total;
305 }
306
307 PlotOrientation orientation = plot.getOrientation();
308 double barW0 = domainAxis.getCategoryMiddle(column, getColumnCount(),
309 dataArea, plot.getDomainAxisEdge())
310 - state.getBarWidth() / 2.0;
311
312 double positiveBase = getBase();
313 double negativeBase = positiveBase;
314
315 for (int i = 0; i < row; i++) {
316 Number v = dataset.getValue(i, column);
317 if (v != null) {
318 double d = v.doubleValue();
319 if (this.renderAsPercentages) {
320 d = d / total;
321 }
322 if (d > 0) {
323 positiveBase = positiveBase + d;
324 }
325 else {
326 negativeBase = negativeBase + d;
327 }
328 }
329 }
330
331 double translatedBase;
332 double translatedValue;
333 boolean positive = (value > 0.0);
334 boolean inverted = rangeAxis.isInverted();
335 RectangleEdge barBase;
336 if (orientation == PlotOrientation.HORIZONTAL) {
337 if (positive && inverted || !positive && !inverted) {
338 barBase = RectangleEdge.RIGHT;
339 }
340 else {
341 barBase = RectangleEdge.LEFT;
342 }
343 }
344 else {
345 if (positive && !inverted || !positive && inverted) {
346 barBase = RectangleEdge.BOTTOM;
347 }
348 else {
349 barBase = RectangleEdge.TOP;
350 }
351 }
352
353 RectangleEdge location = plot.getRangeAxisEdge();
354 if (positive) {
355 translatedBase = rangeAxis.valueToJava2D(positiveBase, dataArea,
356 location);
357 translatedValue = rangeAxis.valueToJava2D(positiveBase + value,
358 dataArea, location);
359 }
360 else {
361 translatedBase = rangeAxis.valueToJava2D(negativeBase, dataArea,
362 location);
363 translatedValue = rangeAxis.valueToJava2D(negativeBase + value,
364 dataArea, location);
365 }
366 double barL0 = Math.min(translatedBase, translatedValue);
367 double barLength = Math.max(Math.abs(translatedValue - translatedBase),
368 getMinimumBarLength());
369
370 Rectangle2D bar = null;
371 if (orientation == PlotOrientation.HORIZONTAL) {
372 bar = new Rectangle2D.Double(barL0, barW0, barLength,
373 state.getBarWidth());
374 }
375 else {
376 bar = new Rectangle2D.Double(barW0, barL0, state.getBarWidth(),
377 barLength);
378 }
379 if (pass == 0) {
380 if (getShadowsVisible()) {
381 boolean pegToBase = (positive && (positiveBase == getBase()))
382 || (!positive && (negativeBase == getBase()));
383 getBarPainter().paintBarShadow(g2, this, row, column, bar,
384 barBase, pegToBase);
385 }
386 }
387 else if (pass == 1) {
388 getBarPainter().paintBar(g2, this, row, column, bar, barBase);
389
390 // add an item entity, if this information is being collected
391 EntityCollection entities = state.getEntityCollection();
392 if (entities != null) {
393 addItemEntity(entities, dataset, row, column, bar);
394 }
395 }
396 else if (pass == 2) {
397 CategoryItemLabelGenerator generator = getItemLabelGenerator(row,
398 column);
399 if (generator != null && isItemLabelVisible(row, column)) {
400 drawItemLabel(g2, dataset, row, column, plot, generator, bar,
401 (value < 0.0));
402 }
403 }
404 }
405
406 /**
407 * Tests this renderer for equality with an arbitrary object.
408 *
409 * @param obj the object (<code>null</code> permitted).
410 *
411 * @return A boolean.
412 */
413 public boolean equals(Object obj) {
414 if (obj == this) {
415 return true;
416 }
417 if (!(obj instanceof StackedBarRenderer)) {
418 return false;
419 }
420 StackedBarRenderer that = (StackedBarRenderer) obj;
421 if (this.renderAsPercentages != that.renderAsPercentages) {
422 return false;
423 }
424 return super.equals(obj);
425 }
426
427 }