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     * StatisticalLineAndShapeRenderer.java
029     * ------------------------------------
030     * (C) Copyright 2005-2008, by Object Refinery Limited and Contributors.
031     *
032     * Original Author:  Mofeed Shahin;
033     * Contributor(s):   David Gilbert (for Object Refinery Limited);
034     *
035     * Changes
036     * -------
037     * 01-Feb-2005 : Version 1, contributed by Mofeed Shahin (DG);
038     * 16-Jun-2005 : Added errorIndicatorPaint to be consistent with
039     *               StatisticalBarRenderer (DG);
040     * ------------- JFREECHART 1.0.x ---------------------------------------------
041     * 11-Apr-2006 : Fixed bug 1468794, error bars drawn incorrectly when rendering
042     *               plots with horizontal orientation (DG);
043     * 25-Sep-2006 : Fixed bug 1562759, constructor ignoring arguments (DG);
044     * 01-Jun-2007 : Return early from drawItem() method if item is not
045     *               visible (DG);
046     * 14-Jun-2007 : If the dataset is not a StatisticalCategoryDataset, revert
047     *               to the drawing behaviour of LineAndShapeRenderer (DG);
048     * 27-Sep-2007 : Added offset option to match new option in
049     *               LineAndShapeRenderer (DG);
050     *
051     */
052    
053    package org.jfree.chart.renderer.category;
054    
055    import java.awt.Graphics2D;
056    import java.awt.Paint;
057    import java.awt.Shape;
058    import java.awt.geom.Line2D;
059    import java.awt.geom.Rectangle2D;
060    import java.io.IOException;
061    import java.io.ObjectInputStream;
062    import java.io.ObjectOutputStream;
063    import java.io.Serializable;
064    
065    import org.jfree.chart.axis.CategoryAxis;
066    import org.jfree.chart.axis.ValueAxis;
067    import org.jfree.chart.entity.EntityCollection;
068    import org.jfree.chart.event.RendererChangeEvent;
069    import org.jfree.chart.plot.CategoryPlot;
070    import org.jfree.chart.plot.PlotOrientation;
071    import org.jfree.data.category.CategoryDataset;
072    import org.jfree.data.statistics.StatisticalCategoryDataset;
073    import org.jfree.io.SerialUtilities;
074    import org.jfree.ui.RectangleEdge;
075    import org.jfree.util.PaintUtilities;
076    import org.jfree.util.PublicCloneable;
077    import org.jfree.util.ShapeUtilities;
078    
079    /**
080     * A renderer that draws shapes for each data item, and lines between data
081     * items.  Each point has a mean value and a standard deviation line. For use
082     * with the {@link CategoryPlot} class.  The example shown
083     * here is generated by the <code>StatisticalLineChartDemo1.java</code> program
084     * included in the JFreeChart Demo Collection:
085     * <br><br>
086     * <img src="../../../../../images/StatisticalLineRendererSample.png"
087     * alt="StatisticalLineRendererSample.png" />
088     */
089    public class StatisticalLineAndShapeRenderer extends LineAndShapeRenderer
090            implements Cloneable, PublicCloneable, Serializable {
091    
092        /** For serialization. */
093        private static final long serialVersionUID = -3557517173697777579L;
094    
095        /** The paint used to show the error indicator. */
096        private transient Paint errorIndicatorPaint;
097    
098        /**
099         * Constructs a default renderer (draws shapes and lines).
100         */
101        public StatisticalLineAndShapeRenderer() {
102            this(true, true);
103        }
104    
105        /**
106         * Constructs a new renderer.
107         *
108         * @param linesVisible  draw lines?
109         * @param shapesVisible  draw shapes?
110         */
111        public StatisticalLineAndShapeRenderer(boolean linesVisible,
112                                               boolean shapesVisible) {
113            super(linesVisible, shapesVisible);
114            this.errorIndicatorPaint = null;
115        }
116    
117        /**
118         * Returns the paint used for the error indicators.
119         *
120         * @return The paint used for the error indicators (possibly
121         *         <code>null</code>).
122         *
123         * @see #setErrorIndicatorPaint(Paint)
124         */
125        public Paint getErrorIndicatorPaint() {
126            return this.errorIndicatorPaint;
127        }
128    
129        /**
130         * Sets the paint used for the error indicators (if <code>null</code>,
131         * the item outline paint is used instead) and sends a
132         * {@link RendererChangeEvent} to all registered listeners.
133         *
134         * @param paint  the paint (<code>null</code> permitted).
135         *
136         * @see #getErrorIndicatorPaint()
137         */
138        public void setErrorIndicatorPaint(Paint paint) {
139            this.errorIndicatorPaint = paint;
140            fireChangeEvent();
141        }
142    
143        /**
144         * Draw a single data item.
145         *
146         * @param g2  the graphics device.
147         * @param state  the renderer state.
148         * @param dataArea  the area in which the data is drawn.
149         * @param plot  the plot.
150         * @param domainAxis  the domain axis.
151         * @param rangeAxis  the range axis.
152         * @param dataset  the dataset (a {@link StatisticalCategoryDataset} is
153         *                 required).
154         * @param row  the row index (zero-based).
155         * @param column  the column index (zero-based).
156         * @param pass  the pass.
157         */
158        public void drawItem(Graphics2D g2,
159                             CategoryItemRendererState state,
160                             Rectangle2D dataArea,
161                             CategoryPlot plot,
162                             CategoryAxis domainAxis,
163                             ValueAxis rangeAxis,
164                             CategoryDataset dataset,
165                             int row,
166                             int column,
167                             int pass) {
168    
169            // do nothing if item is not visible
170            if (!getItemVisible(row, column)) {
171                return;
172            }
173    
174            // nothing is drawn for null...
175            Number v = dataset.getValue(row, column);
176            if (v == null) {
177                return;
178            }
179    
180            // if the dataset is not a StatisticalCategoryDataset then just revert
181            // to the superclass (LineAndShapeRenderer) behaviour...
182            if (!(dataset instanceof StatisticalCategoryDataset)) {
183                super.drawItem(g2, state, dataArea, plot, domainAxis, rangeAxis,
184                        dataset, row, column, pass);
185                return;
186            }
187    
188            StatisticalCategoryDataset statData
189                    = (StatisticalCategoryDataset) dataset;
190    
191            Number meanValue = statData.getMeanValue(row, column);
192    
193            PlotOrientation orientation = plot.getOrientation();
194    
195            // current data point...
196            double x1;
197            if (getUseSeriesOffset()) {
198                x1 = domainAxis.getCategorySeriesMiddle(dataset.getColumnKey(
199                        column), dataset.getRowKey(row), dataset, getItemMargin(),
200                        dataArea, plot.getDomainAxisEdge());
201            }
202            else {
203                x1 = domainAxis.getCategoryMiddle(column, getColumnCount(),
204                        dataArea, plot.getDomainAxisEdge());
205            }
206    
207            double y1 = rangeAxis.valueToJava2D(meanValue.doubleValue(), dataArea,
208                    plot.getRangeAxisEdge());
209    
210            Shape shape = getItemShape(row, column);
211            if (orientation == PlotOrientation.HORIZONTAL) {
212                shape = ShapeUtilities.createTranslatedShape(shape, y1, x1);
213            }
214            else if (orientation == PlotOrientation.VERTICAL) {
215                shape = ShapeUtilities.createTranslatedShape(shape, x1, y1);
216            }
217            if (getItemShapeVisible(row, column)) {
218    
219                if (getItemShapeFilled(row, column)) {
220                    g2.setPaint(getItemPaint(row, column));
221                    g2.fill(shape);
222                }
223                else {
224                    if (getUseOutlinePaint()) {
225                        g2.setPaint(getItemOutlinePaint(row, column));
226                    }
227                    else {
228                        g2.setPaint(getItemPaint(row, column));
229                    }
230                    g2.setStroke(getItemOutlineStroke(row, column));
231                    g2.draw(shape);
232                }
233            }
234    
235            if (getItemLineVisible(row, column)) {
236                if (column != 0) {
237    
238                    Number previousValue = statData.getValue(row, column - 1);
239                    if (previousValue != null) {
240    
241                        // previous data point...
242                        double previous = previousValue.doubleValue();
243                        double x0;
244                        if (getUseSeriesOffset()) {
245                            x0 = domainAxis.getCategorySeriesMiddle(
246                                    dataset.getColumnKey(column - 1),
247                                    dataset.getRowKey(row), dataset,
248                                    getItemMargin(), dataArea,
249                                    plot.getDomainAxisEdge());
250                        }
251                        else {
252                            x0 = domainAxis.getCategoryMiddle(column - 1,
253                                    getColumnCount(), dataArea,
254                                    plot.getDomainAxisEdge());
255                        }
256                        double y0 = rangeAxis.valueToJava2D(previous, dataArea,
257                                plot.getRangeAxisEdge());
258    
259                        Line2D line = null;
260                        if (orientation == PlotOrientation.HORIZONTAL) {
261                            line = new Line2D.Double(y0, x0, y1, x1);
262                        }
263                        else if (orientation == PlotOrientation.VERTICAL) {
264                            line = new Line2D.Double(x0, y0, x1, y1);
265                        }
266                        g2.setPaint(getItemPaint(row, column));
267                        g2.setStroke(getItemStroke(row, column));
268                        g2.draw(line);
269                    }
270                }
271            }
272    
273            RectangleEdge yAxisLocation = plot.getRangeAxisEdge();
274            g2.setPaint(getItemPaint(row, column));
275    
276            //standard deviation lines
277            double valueDelta = statData.getStdDevValue(row, column).doubleValue();
278    
279            double highVal, lowVal;
280            if ((meanValue.doubleValue() + valueDelta)
281                    > rangeAxis.getRange().getUpperBound()) {
282                highVal = rangeAxis.valueToJava2D(
283                        rangeAxis.getRange().getUpperBound(), dataArea,
284                        yAxisLocation);
285            }
286            else {
287                highVal = rangeAxis.valueToJava2D(meanValue.doubleValue()
288                        + valueDelta, dataArea, yAxisLocation);
289            }
290    
291            if ((meanValue.doubleValue() + valueDelta)
292                    < rangeAxis.getRange().getLowerBound()) {
293                lowVal = rangeAxis.valueToJava2D(
294                        rangeAxis.getRange().getLowerBound(), dataArea,
295                        yAxisLocation);
296            }
297            else {
298                lowVal = rangeAxis.valueToJava2D(meanValue.doubleValue()
299                        - valueDelta, dataArea, yAxisLocation);
300            }
301    
302            if (this.errorIndicatorPaint != null) {
303                g2.setPaint(this.errorIndicatorPaint);
304            }
305            else {
306                g2.setPaint(getItemPaint(row, column));
307            }
308            Line2D line = new Line2D.Double();
309            if (orientation == PlotOrientation.HORIZONTAL) {
310                line.setLine(lowVal, x1, highVal, x1);
311                g2.draw(line);
312                line.setLine(lowVal, x1 - 5.0d, lowVal, x1 + 5.0d);
313                g2.draw(line);
314                line.setLine(highVal, x1 - 5.0d, highVal, x1 + 5.0d);
315                g2.draw(line);
316            }
317            else {  // PlotOrientation.VERTICAL
318                line.setLine(x1, lowVal, x1, highVal);
319                g2.draw(line);
320                line.setLine(x1 - 5.0d, highVal, x1 + 5.0d, highVal);
321                g2.draw(line);
322                line.setLine(x1 - 5.0d, lowVal, x1 + 5.0d, lowVal);
323                g2.draw(line);
324            }
325    
326            // draw the item label if there is one...
327            if (isItemLabelVisible(row, column)) {
328                if (orientation == PlotOrientation.HORIZONTAL) {
329                    drawItemLabel(g2, orientation, dataset, row, column,
330                            y1, x1, (meanValue.doubleValue() < 0.0));
331                }
332                else if (orientation == PlotOrientation.VERTICAL) {
333                    drawItemLabel(g2, orientation, dataset, row, column,
334                            x1, y1, (meanValue.doubleValue() < 0.0));
335                }
336            }
337    
338            // add an item entity, if this information is being collected
339            EntityCollection entities = state.getEntityCollection();
340            if (entities != null && shape != null) {
341                addItemEntity(entities, dataset, row, column, shape);
342            }
343    
344        }
345    
346        /**
347         * Tests this renderer for equality with an arbitrary object.
348         *
349         * @param obj  the object (<code>null</code> permitted).
350         *
351         * @return A boolean.
352         */
353        public boolean equals(Object obj) {
354            if (obj == this) {
355                return true;
356            }
357            if (!(obj instanceof StatisticalLineAndShapeRenderer)) {
358                return false;
359            }
360            StatisticalLineAndShapeRenderer that
361                    = (StatisticalLineAndShapeRenderer) obj;
362            if (!PaintUtilities.equal(this.errorIndicatorPaint,
363                    that.errorIndicatorPaint)) {
364                return false;
365            }
366            return super.equals(obj);
367        }
368    
369        /**
370         * Provides serialization support.
371         *
372         * @param stream  the output stream.
373         *
374         * @throws IOException  if there is an I/O error.
375         */
376        private void writeObject(ObjectOutputStream stream) throws IOException {
377            stream.defaultWriteObject();
378            SerialUtilities.writePaint(this.errorIndicatorPaint, stream);
379        }
380    
381        /**
382         * Provides serialization support.
383         *
384         * @param stream  the input stream.
385         *
386         * @throws IOException  if there is an I/O error.
387         * @throws ClassNotFoundException  if there is a classpath problem.
388         */
389        private void readObject(ObjectInputStream stream)
390                throws IOException, ClassNotFoundException {
391            stream.defaultReadObject();
392            this.errorIndicatorPaint = SerialUtilities.readPaint(stream);
393        }
394    
395    }