001/* ===========================================================
002 * JFreeChart : a free chart library for the Java(tm) platform
003 * ===========================================================
004 *
005 * (C) Copyright 2000-2020, 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 * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. 
025 * Other names may be trademarks of their respective owners.]
026 *
027 * ------------
028 * LogAxis.java
029 * ------------
030 * (C) Copyright 2006-2016, by Object Refinery Limited and Contributors.
031 *
032 * Original Author:  David Gilbert (for Object Refinery Limited);
033 * Contributor(s):   Andrew Mickish (patch 1868745);
034 *                   Peter Kolb (patches 1934255 and 2603321);
035 *
036 * Changes
037 * -------
038 * 24-Aug-2006 : Version 1 (DG);
039 * 22-Mar-2007 : Use defaultAutoArrange attribute (DG);
040 * 02-Aug-2007 : Fixed zooming bug, added support for margins (DG);
041 * 14-Feb-2008 : Changed default minorTickCount to 9 - see bug report
042 *               1892419 (DG);
043 * 15-Feb-2008 : Applied a variation of patch 1868745 by Andrew Mickish to
044 *               fix a labelling bug when the axis appears at the top or
045 *               right of the chart (DG);
046 * 19-Mar-2008 : Applied patch 1902418 by Andrew Mickish to fix bug in tick
047 *               labels for vertical axis (DG);
048 * 26-Mar-2008 : Changed createTickLabel() method from private to protected -
049 *               see patch 1918209 by Andrew Mickish (DG);
050 * 25-Sep-2008 : Moved minor tick fields up to superclass, see patch 1934255
051 *               by Peter Kolb (DG);
052 * 14-Jan-2009 : Fetch minor ticks from TickUnit, and corrected
053 *               createLogTickUnits() (DG);
054 * 21-Jan-2009 : No need to call setMinorTickCount() in constructor (DG);
055 * 19-Mar-2009 : Added entity support - see patch 2603321 by Peter Kolb (DG);
056 * 30-Mar-2009 : Added pan(double) method (DG);
057 * 28-Oct-2011 : Fixed endless loop for 0 TickUnit, # 3429707 (MH);
058 * 02-Jul-2013 : Use ParamChecks (DG);
059 * 01-Aug-2013 : Added attributedLabel override to support superscripts,
060 *               subscripts and more (DG);
061 * 18-Mar-2014 : Add support for super-scripted tick labels (DG);
062 * 
063 */
064
065package org.jfree.chart.axis;
066
067import java.awt.Font;
068import java.awt.Graphics2D;
069import java.awt.font.FontRenderContext;
070import java.awt.font.LineMetrics;
071import java.awt.font.TextAttribute;
072import java.awt.geom.Rectangle2D;
073import java.text.AttributedString;
074import java.text.DecimalFormat;
075import java.text.Format;
076import java.text.NumberFormat;
077import java.util.ArrayList;
078import java.util.List;
079
080import org.jfree.chart.event.AxisChangeEvent;
081import org.jfree.chart.plot.Plot;
082import org.jfree.chart.plot.PlotRenderingInfo;
083import org.jfree.chart.plot.ValueAxisPlot;
084import org.jfree.chart.ui.RectangleEdge;
085import org.jfree.chart.ui.RectangleInsets;
086import org.jfree.chart.ui.TextAnchor;
087import org.jfree.chart.util.AttrStringUtils;
088import org.jfree.chart.util.ObjectUtils;
089import org.jfree.chart.util.Args;
090import org.jfree.data.Range;
091
092/**
093 * A numerical axis that uses a logarithmic scale.  The class is an
094 * alternative to the {@link LogarithmicAxis} class.
095 *
096 * @since 1.0.7
097 */
098public class LogAxis extends ValueAxis {
099
100    /** The logarithm base. */
101    private double base = 10.0;
102
103    /** The logarithm of the base value - cached for performance. */
104    private double baseLog = Math.log(10.0);
105
106    /** 
107     * The base symbol to display (if {@code null} then the numerical
108     * value of the base is displayed).
109     */
110    private String baseSymbol = null;
111    
112    /** 
113     * The formatter to use for the base value when the base is displayed
114     * as a numerical value.
115     */
116    private Format baseFormatter = new DecimalFormat("0");
117    
118    /**  The smallest value permitted on the axis. */
119    private double smallestValue = 1E-100;
120
121    /** The current tick unit. */
122    private NumberTickUnit tickUnit;
123
124    /** The override number format. */
125    private NumberFormat numberFormatOverride;
126
127    /**
128     * Creates a new {@code LogAxis} with no label.
129     */
130    public LogAxis() {
131        this(null);
132    }
133
134    /**
135     * Creates a new {@code LogAxis} with the given label.
136     *
137     * @param label  the axis label ({@code null} permitted).
138     */
139    public LogAxis(String label) {
140        super(label, new NumberTickUnitSource());
141        setDefaultAutoRange(new Range(0.01, 1.0));
142        this.tickUnit = new NumberTickUnit(1.0, new DecimalFormat("0.#"), 10);
143    }
144
145    /**
146     * Returns the base for the logarithm calculation.  The default value is
147     * {@code 10.0}.
148     *
149     * @return The base for the logarithm calculation.
150     *
151     * @see #setBase(double)
152     */
153    public double getBase() {
154        return this.base;
155    }
156
157    /**
158     * Sets the base for the logarithm calculation and sends a change event to
159     * all registered listeners.
160     *
161     * @param base  the base value (must be > 1.0).
162     *
163     * @see #getBase()
164     */
165    public void setBase(double base) {
166        if (base <= 1.0) {
167            throw new IllegalArgumentException("Requires 'base' > 1.0.");
168        }
169        this.base = base;
170        this.baseLog = Math.log(base);
171        fireChangeEvent();
172    }
173
174    /**
175     * Returns the symbol used to represent the base of the logarithmic scale
176     * for the axis.  If this is {@code null} (the default) then the 
177     * numerical value of the base is displayed.
178     * 
179     * @return The base symbol (possibly {@code null}).
180     * 
181     * @since 1.0.18
182     */
183    public String getBaseSymbol() {
184        return this.baseSymbol;
185    }
186    
187    /**
188     * Sets the symbol used to represent the base value of the logarithmic 
189     * scale and sends a change event to all registered listeners.
190     * 
191     * @param symbol  the symbol ({@code null} permitted).
192     * 
193     * @since 1.0.18
194     */
195    public void setBaseSymbol(String symbol) {
196        this.baseSymbol = symbol;
197        fireChangeEvent();
198    }
199    
200    /**
201     * Returns the formatter used to format the base value of the logarithmic
202     * scale when it is displayed numerically.  The default value is
203     * {@code new DecimalFormat("0")}.
204     * 
205     * @return The base formatter (never {@code null}).
206     * 
207     * @since 1.0.18
208     */
209    public Format getBaseFormatter() {
210        return this.baseFormatter;
211    }
212    
213    /**
214     * Sets the formatter used to format the base value of the logarithmic 
215     * scale when it is displayed numerically and sends a change event to all
216     * registered listeners.
217     * 
218     * @param formatter  the formatter ({@code null} not permitted).
219     * 
220     * @since 1.0.18
221     */
222    public void setBaseFormatter(Format formatter) {
223        Args.nullNotPermitted(formatter, "formatter");
224        this.baseFormatter = formatter;
225        fireChangeEvent();
226    }
227    
228    /**
229     * Returns the smallest value represented by the axis.
230     *
231     * @return The smallest value represented by the axis.
232     *
233     * @see #setSmallestValue(double)
234     */
235    public double getSmallestValue() {
236        return this.smallestValue;
237    }
238
239    /**
240     * Sets the smallest value represented by the axis and sends a change event
241     * to all registered listeners.
242     *
243     * @param value  the value.
244     *
245     * @see #getSmallestValue()
246     */
247    public void setSmallestValue(double value) {
248        if (value <= 0.0) {
249            throw new IllegalArgumentException("Requires 'value' > 0.0.");
250        }
251        this.smallestValue = value;
252        fireChangeEvent();
253    }
254
255    /**
256     * Returns the current tick unit.
257     *
258     * @return The current tick unit.
259     *
260     * @see #setTickUnit(NumberTickUnit)
261     */
262    public NumberTickUnit getTickUnit() {
263        return this.tickUnit;
264    }
265
266    /**
267     * Sets the tick unit for the axis and sends an {@link AxisChangeEvent} to
268     * all registered listeners.  A side effect of calling this method is that
269     * the "auto-select" feature for tick units is switched off (you can
270     * restore it using the {@link ValueAxis#setAutoTickUnitSelection(boolean)}
271     * method).
272     *
273     * @param unit  the new tick unit ({@code null} not permitted).
274     *
275     * @see #getTickUnit()
276     */
277    public void setTickUnit(NumberTickUnit unit) {
278        // defer argument checking...
279        setTickUnit(unit, true, true);
280    }
281
282    /**
283     * Sets the tick unit for the axis and, if requested, sends an
284     * {@link AxisChangeEvent} to all registered listeners.  In addition, an
285     * option is provided to turn off the "auto-select" feature for tick units
286     * (you can restore it using the
287     * {@link ValueAxis#setAutoTickUnitSelection(boolean)} method).
288     *
289     * @param unit  the new tick unit ({@code null} not permitted).
290     * @param notify  notify listeners?
291     * @param turnOffAutoSelect  turn off the auto-tick selection?
292     *
293     * @see #getTickUnit()
294     */
295    public void setTickUnit(NumberTickUnit unit, boolean notify,
296            boolean turnOffAutoSelect) {
297        Args.nullNotPermitted(unit, "unit");
298        this.tickUnit = unit;
299        if (turnOffAutoSelect) {
300            setAutoTickUnitSelection(false, false);
301        }
302        if (notify) {
303            fireChangeEvent();
304        }
305    }
306
307    /**
308     * Returns the number format override.  If this is non-{@code null}, 
309     * then it will be used to format the numbers on the axis.
310     *
311     * @return The number formatter (possibly {@code null}).
312     *
313     * @see #setNumberFormatOverride(NumberFormat)
314     */
315    public NumberFormat getNumberFormatOverride() {
316        return this.numberFormatOverride;
317    }
318
319    /**
320     * Sets the number format override and sends a change event to all 
321     * registered listeners.  If this is non-{@code null}, then it will be
322     * used to format the numbers on the axis.
323     *
324     * @param formatter  the number formatter ({@code null} permitted).
325     *
326     * @see #getNumberFormatOverride()
327     */
328    public void setNumberFormatOverride(NumberFormat formatter) {
329        this.numberFormatOverride = formatter;
330        fireChangeEvent();
331    }
332
333    /**
334     * Calculates the log of the given value, using the current base.
335     *
336     * @param value  the value.
337     *
338     * @return The log of the given value.
339     *
340     * @see #calculateValue(double)
341     * @see #getBase()
342     */
343    public double calculateLog(double value) {
344        return Math.log(value) / this.baseLog;
345    }
346
347    /**
348     * Calculates the value from a given log.
349     *
350     * @param log  the log value.
351     *
352     * @return The value with the given log.
353     *
354     * @see #calculateLog(double)
355     * @see #getBase()
356     */
357    public double calculateValue(double log) {
358        return Math.pow(this.base, log);
359    }
360    
361    private double calculateValueNoINF(double log) {
362        double result = calculateValue(log);
363        if (Double.isInfinite(result)) {
364            result = Double.MAX_VALUE;
365        }
366        if (result <= 0.0) {
367            result = Double.MIN_VALUE;
368        }
369        return result;
370    }
371
372    /**
373     * Converts a Java2D coordinate to an axis value, assuming that the
374     * axis is aligned to the specified {@code edge} of the {@code area}.
375     *
376     * @param java2DValue  the Java2D coordinate.
377     * @param area  the area for plotting data ({@code null} not 
378     *     permitted).
379     * @param edge  the edge that the axis is aligned to ({@code null} not
380     *     permitted).
381     *
382     * @return A value along the axis scale.
383     */
384    @Override
385    public double java2DToValue(double java2DValue, Rectangle2D area,
386            RectangleEdge edge) {
387
388        Range range = getRange();
389        double axisMin = calculateLog(Math.max(this.smallestValue, 
390                range.getLowerBound()));
391        double axisMax = calculateLog(range.getUpperBound());
392
393        double min = 0.0;
394        double max = 0.0;
395        if (RectangleEdge.isTopOrBottom(edge)) {
396            min = area.getX();
397            max = area.getMaxX();
398        } else if (RectangleEdge.isLeftOrRight(edge)) {
399            min = area.getMaxY();
400            max = area.getY();
401        }
402        double log;
403        if (isInverted()) {
404            log = axisMax - (java2DValue - min) / (max - min)
405                    * (axisMax - axisMin);
406        } else {
407            log = axisMin + (java2DValue - min) / (max - min)
408                    * (axisMax - axisMin);
409        }
410        return calculateValue(log);
411    }
412
413    /**
414     * Converts a value on the axis scale to a Java2D coordinate relative to
415     * the given {@code area}, based on the axis running along the
416     * specified {@code edge}.
417     *
418     * @param value  the data value.
419     * @param area  the area ({@code null} not permitted).
420     * @param edge  the edge ({@code null} not permitted).
421     *
422     * @return The Java2D coordinate corresponding to {@code value}.
423     */
424    @Override
425    public double valueToJava2D(double value, Rectangle2D area,
426            RectangleEdge edge) {
427
428        Range range = getRange();
429        double axisMin = calculateLog(range.getLowerBound());
430        double axisMax = calculateLog(range.getUpperBound());
431        value = calculateLog(value);
432
433        double min = 0.0;
434        double max = 0.0;
435        if (RectangleEdge.isTopOrBottom(edge)) {
436            min = area.getX();
437            max = area.getMaxX();
438        } else if (RectangleEdge.isLeftOrRight(edge)) {
439            max = area.getMinY();
440            min = area.getMaxY();
441        }
442        if (isInverted()) {
443            return max
444                   - ((value - axisMin) / (axisMax - axisMin)) * (max - min);
445        } else {
446            return min
447                   + ((value - axisMin) / (axisMax - axisMin)) * (max - min);
448        }
449    }
450
451    /**
452     * Configures the axis.  This method is typically called when an axis
453     * is assigned to a new plot.
454     */
455    @Override
456    public void configure() {
457        if (isAutoRange()) {
458            autoAdjustRange();
459        }
460    }
461
462    /**
463     * Adjusts the axis range to match the data range that the axis is
464     * required to display.
465     */
466    @Override
467    protected void autoAdjustRange() {
468        Plot plot = getPlot();
469        if (plot == null) {
470            return;  // no plot, no data
471        }
472
473        if (plot instanceof ValueAxisPlot) {
474            ValueAxisPlot vap = (ValueAxisPlot) plot;
475
476            Range r = vap.getDataRange(this);
477            if (r == null) {
478                r = getDefaultAutoRange();
479            }
480
481            double upper = r.getUpperBound();
482            double lower = Math.max(r.getLowerBound(), this.smallestValue);
483            double range = upper - lower;
484
485            // if fixed auto range, then derive lower bound...
486            double fixedAutoRange = getFixedAutoRange();
487            if (fixedAutoRange > 0.0) {
488                lower = Math.max(upper - fixedAutoRange, this.smallestValue);
489            }
490            else {
491                // ensure the autorange is at least <minRange> in size...
492                double minRange = getAutoRangeMinimumSize();
493                if (range < minRange) {
494                    double expand = (minRange - range) / 2;
495                    upper = upper + expand;
496                    lower = lower - expand;
497                }
498
499                // apply the margins - these should apply to the exponent range
500                double logUpper = calculateLog(upper);
501                double logLower = calculateLog(lower);
502                double logRange = logUpper - logLower;
503                logUpper = logUpper + getUpperMargin() * logRange;
504                logLower = logLower - getLowerMargin() * logRange;
505                upper = calculateValueNoINF(logUpper);
506                lower = calculateValueNoINF(logLower);
507            }
508            setRange(new Range(lower, upper), false, false);
509        }
510
511    }
512
513    /**
514     * Draws the axis on a Java 2D graphics device (such as the screen or a
515     * printer).
516     *
517     * @param g2  the graphics device ({@code null} not permitted).
518     * @param cursor  the cursor location (determines where to draw the axis).
519     * @param plotArea  the area within which the axes and plot should be drawn.
520     * @param dataArea  the area within which the data should be drawn.
521     * @param edge  the axis location ({@code null} not permitted).
522     * @param plotState  collects information about the plot ({@code null} 
523     *         permitted).
524     *
525     * @return The axis state (never {@code null}).
526     */
527    @Override
528    public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea,
529            Rectangle2D dataArea, RectangleEdge edge,
530            PlotRenderingInfo plotState) {
531
532        AxisState state;
533        // if the axis is not visible, don't draw it...
534        if (!isVisible()) {
535            state = new AxisState(cursor);
536            // even though the axis is not visible, we need ticks for the
537            // gridlines...
538            List ticks = refreshTicks(g2, state, dataArea, edge);
539            state.setTicks(ticks);
540            return state;
541        }
542        state = drawTickMarksAndLabels(g2, cursor, plotArea, dataArea, edge);
543        if (getAttributedLabel() != null) {
544            state = drawAttributedLabel(getAttributedLabel(), g2, plotArea, 
545                    dataArea, edge, state);
546            
547        } else {
548            state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state);
549        }
550        createAndAddEntity(cursor, state, dataArea, edge, plotState);
551        return state;
552    }
553
554    /**
555     * Calculates the positions of the tick labels for the axis, storing the
556     * results in the tick label list (ready for drawing).
557     *
558     * @param g2  the graphics device.
559     * @param state  the axis state.
560     * @param dataArea  the area in which the plot should be drawn.
561     * @param edge  the location of the axis.
562     *
563     * @return A list of ticks.
564     */
565    @Override
566    public List refreshTicks(Graphics2D g2, AxisState state,
567            Rectangle2D dataArea, RectangleEdge edge) {
568        List result = new java.util.ArrayList();
569        if (RectangleEdge.isTopOrBottom(edge)) {
570            result = refreshTicksHorizontal(g2, dataArea, edge);
571        }
572        else if (RectangleEdge.isLeftOrRight(edge)) {
573            result = refreshTicksVertical(g2, dataArea, edge);
574        }
575        return result;
576    }
577    
578    /**
579     * Returns a list of ticks for an axis at the top or bottom of the chart.
580     *
581     * @param g2  the graphics device ({@code null} not permitted).
582     * @param dataArea  the data area ({@code null} not permitted).
583     * @param edge  the edge ({@code null} not permitted).
584     *
585     * @return A list of ticks.
586     */
587    protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea,
588            RectangleEdge edge) {
589
590        Range range = getRange();
591        List ticks = new ArrayList();
592        Font tickLabelFont = getTickLabelFont();
593        g2.setFont(tickLabelFont);
594        TextAnchor textAnchor;
595        if (edge == RectangleEdge.TOP) {
596            textAnchor = TextAnchor.BOTTOM_CENTER;
597        }
598        else {
599            textAnchor = TextAnchor.TOP_CENTER;
600        }
601
602        if (isAutoTickUnitSelection()) {
603            selectAutoTickUnit(g2, dataArea, edge);
604        }
605        int minorTickCount = this.tickUnit.getMinorTickCount();
606        double unit = getTickUnit().getSize();
607        double index = Math.ceil(calculateLog(getRange().getLowerBound()) 
608                / unit);
609        double start = index * unit;
610        double end = calculateLog(getUpperBound());
611        double current = start;
612        boolean hasTicks = (this.tickUnit.getSize() > 0.0)
613                           && !Double.isInfinite(start);
614        while (hasTicks && current <= end) {
615            double v = calculateValueNoINF(current);
616            if (range.contains(v)) {
617                ticks.add(new LogTick(TickType.MAJOR, v, createTickLabel(v),
618                        textAnchor));
619            }
620            // add minor ticks (for gridlines)
621            double next = Math.pow(this.base, current
622                    + this.tickUnit.getSize());
623            for (int i = 1; i < minorTickCount; i++) {
624                double minorV = v + i * ((next - v) / minorTickCount);
625                if (range.contains(minorV)) {
626                    ticks.add(new LogTick(TickType.MINOR, minorV, null,
627                            textAnchor));
628                }
629            }
630            current = current + this.tickUnit.getSize();
631        }
632        return ticks;
633    }
634
635    /**
636     * Returns a list of ticks for an axis at the left or right of the chart.
637     *
638     * @param g2  the graphics device ({@code null} not permitted).
639     * @param dataArea  the data area ({@code null} not permitted).
640     * @param edge  the edge that the axis is aligned to ({@code null} 
641     *     not permitted).
642     *
643     * @return A list of ticks.
644     */
645    protected List refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea,
646            RectangleEdge edge) {
647
648        Range range = getRange();
649        List ticks = new ArrayList();
650        Font tickLabelFont = getTickLabelFont();
651        g2.setFont(tickLabelFont);
652        TextAnchor textAnchor;
653        if (edge == RectangleEdge.RIGHT) {
654            textAnchor = TextAnchor.CENTER_LEFT;
655        }
656        else {
657            textAnchor = TextAnchor.CENTER_RIGHT;
658        }
659
660        if (isAutoTickUnitSelection()) {
661            selectAutoTickUnit(g2, dataArea, edge);
662        }
663        int minorTickCount = this.tickUnit.getMinorTickCount();
664        double unit = getTickUnit().getSize();
665        double index = Math.ceil(calculateLog(getRange().getLowerBound()) 
666                / unit);
667        double start = index * unit;
668        double end = calculateLog(getUpperBound());
669        double current = start;
670        boolean hasTicks = (this.tickUnit.getSize() > 0.0)
671                           && !Double.isInfinite(start);
672        while (hasTicks && current <= end) {
673            double v = calculateValueNoINF(current);
674            if (range.contains(v)) {
675                ticks.add(new LogTick(TickType.MAJOR, v, createTickLabel(v),
676                        textAnchor));
677            }
678            // add minor ticks (for gridlines)
679            double next = Math.pow(this.base, current
680                    + this.tickUnit.getSize());
681            for (int i = 1; i < minorTickCount; i++) {
682                double minorV = v + i * ((next - v) / minorTickCount);
683                if (range.contains(minorV)) {
684                    ticks.add(new LogTick(TickType.MINOR, minorV, null,
685                            textAnchor));
686                }
687            }
688            current = current + this.tickUnit.getSize();
689        }
690        return ticks;
691    }
692
693    /**
694     * Selects an appropriate tick value for the axis.  The strategy is to
695     * display as many ticks as possible (selected from an array of 'standard'
696     * tick units) without the labels overlapping.
697     *
698     * @param g2  the graphics device ({@code null} not permitted).
699     * @param dataArea  the area defined by the axes ({@code null} not 
700     *     permitted).
701     * @param edge  the axis location ({@code null} not permitted).
702     *
703     * @since 1.0.7
704     */
705    protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea,
706            RectangleEdge edge) {
707        if (RectangleEdge.isTopOrBottom(edge)) {
708            selectHorizontalAutoTickUnit(g2, dataArea, edge);
709        }
710        else if (RectangleEdge.isLeftOrRight(edge)) {
711            selectVerticalAutoTickUnit(g2, dataArea, edge);
712        }
713    }
714
715    /**
716     * Selects an appropriate tick value for the axis.  The strategy is to
717     * display as many ticks as possible (selected from an array of 'standard'
718     * tick units) without the labels overlapping.
719     *
720     * @param g2  the graphics device.
721     * @param dataArea  the area defined by the axes.
722     * @param edge  the axis location.
723     *
724     * @since 1.0.7
725     */
726    protected void selectHorizontalAutoTickUnit(Graphics2D g2,
727            Rectangle2D dataArea, RectangleEdge edge) {
728
729        // select a tick unit that is the next one bigger than the current
730        // (log) range divided by 50
731        Range range = getRange();
732        double logAxisMin = calculateLog(Math.max(this.smallestValue, 
733                range.getLowerBound()));
734        double logAxisMax = calculateLog(range.getUpperBound());
735        double size = (logAxisMax - logAxisMin) / 50;
736        TickUnitSource tickUnits = getStandardTickUnits();
737        TickUnit candidate = tickUnits.getCeilingTickUnit(size);
738        TickUnit prevCandidate = candidate;
739        boolean found = false;
740        while (!found) {
741        // while the tick labels overlap and there are more tick sizes available,
742            // choose the next bigger label
743            this.tickUnit = (NumberTickUnit) candidate;
744            double tickLabelWidth = estimateMaximumTickLabelWidth(g2, 
745                    candidate);
746            // what is the available space for one unit?
747            double candidateWidth = exponentLengthToJava2D(candidate.getSize(), 
748                    dataArea, edge);
749            if (tickLabelWidth < candidateWidth) {
750                found = true;
751            } else if (Double.isNaN(candidateWidth)) {
752                candidate = prevCandidate;
753                found = true;
754            } else {
755                prevCandidate = candidate;
756                candidate = tickUnits.getLargerTickUnit(prevCandidate);
757                if (candidate.equals(prevCandidate)) {
758                    found = true;  // there are no more candidates
759                }
760            }
761        } 
762        setTickUnit((NumberTickUnit) candidate, false, false);
763    }
764
765    /**
766     * Converts a length in data coordinates into the corresponding length in
767     * Java2D coordinates.
768     *
769     * @param length  the length.
770     * @param area  the plot area.
771     * @param edge  the edge along which the axis lies.
772     *
773     * @return The length in Java2D coordinates.
774     *
775     * @since 1.0.7
776     */
777    public double exponentLengthToJava2D(double length, Rectangle2D area,
778                                RectangleEdge edge) {
779        double one = valueToJava2D(calculateValueNoINF(1.0), area, edge);
780        double l = valueToJava2D(calculateValueNoINF(length + 1.0), area, edge);
781        return Math.abs(l - one);
782    }
783
784    /**
785     * Selects an appropriate tick value for the axis.  The strategy is to
786     * display as many ticks as possible (selected from an array of 'standard'
787     * tick units) without the labels overlapping.
788     *
789     * @param g2  the graphics device.
790     * @param dataArea  the area in which the plot should be drawn.
791     * @param edge  the axis location.
792     *
793     * @since 1.0.7
794     */
795    protected void selectVerticalAutoTickUnit(Graphics2D g2, 
796            Rectangle2D dataArea, RectangleEdge edge) {
797        // select a tick unit that is the next one bigger than the current
798        // (log) range divided by 50
799        Range range = getRange();
800        double logAxisMin = calculateLog(Math.max(this.smallestValue, 
801                range.getLowerBound()));
802        double logAxisMax = calculateLog(range.getUpperBound());
803        double size = (logAxisMax - logAxisMin) / 50;
804        TickUnitSource tickUnits = getStandardTickUnits();
805        TickUnit candidate = tickUnits.getCeilingTickUnit(size);
806        TickUnit prevCandidate = candidate;
807        boolean found = false;
808        while (!found) {
809        // while the tick labels overlap and there are more tick sizes available,
810            // choose the next bigger label
811            this.tickUnit = (NumberTickUnit) candidate;
812            double tickLabelHeight = estimateMaximumTickLabelHeight(g2);
813            // what is the available space for one unit?
814            double candidateHeight = exponentLengthToJava2D(candidate.getSize(), 
815                    dataArea, edge);
816            if (tickLabelHeight < candidateHeight) {
817                found = true;
818            } else if (Double.isNaN(candidateHeight)) {
819                candidate = prevCandidate;
820                found = true;
821            } else {
822                prevCandidate = candidate;
823                candidate = tickUnits.getLargerTickUnit(prevCandidate);
824                if (candidate.equals(prevCandidate)) {
825                    found = true;  // there are no more candidates
826                }
827            }
828        } 
829        setTickUnit((NumberTickUnit) candidate, false, false);
830    }
831
832    /**
833     * Creates a tick label for the specified value based on the current
834     * tick unit (used for formatting the exponent).
835     *
836     * @param value  the value.
837     *
838     * @return The label.
839     *
840     * @since 1.0.18
841     */
842    protected AttributedString createTickLabel(double value) {
843        if (this.numberFormatOverride != null) {
844            return new AttributedString(
845                    this.numberFormatOverride.format(value));
846        } else {
847            String baseStr = this.baseSymbol;
848            if (baseStr == null) {
849                baseStr = this.baseFormatter.format(this.base);
850            }
851            double logy = calculateLog(value);
852            String exponentStr = getTickUnit().valueToString(logy);
853            AttributedString as = new AttributedString(baseStr + exponentStr);
854            as.addAttributes(getTickLabelFont().getAttributes(), 0, (baseStr 
855                    + exponentStr).length());
856            as.addAttribute(TextAttribute.SUPERSCRIPT, 
857                    TextAttribute.SUPERSCRIPT_SUPER, baseStr.length(), 
858                    baseStr.length() + exponentStr.length());
859            return as;
860        }
861    }
862
863    /**
864     * Estimates the maximum tick label height.
865     *
866     * @param g2  the graphics device.
867     *
868     * @return The maximum height.
869     *
870     * @since 1.0.7
871     */
872    protected double estimateMaximumTickLabelHeight(Graphics2D g2) {
873        RectangleInsets tickLabelInsets = getTickLabelInsets();
874        double result = tickLabelInsets.getTop() + tickLabelInsets.getBottom();
875
876        Font tickLabelFont = getTickLabelFont();
877        FontRenderContext frc = g2.getFontRenderContext();
878        result += tickLabelFont.getLineMetrics("123", frc).getHeight();
879        return result;
880    }
881
882    /**
883     * Estimates the maximum width of the tick labels, assuming the specified
884     * tick unit is used.
885     * <P>
886     * Rather than computing the string bounds of every tick on the axis, we
887     * just look at two values: the lower bound and the upper bound for the
888     * axis.  These two values will usually be representative.
889     *
890     * @param g2  the graphics device.
891     * @param unit  the tick unit to use for calculation.
892     *
893     * @return The estimated maximum width of the tick labels.
894     *
895     * @since 1.0.7
896     */
897    protected double estimateMaximumTickLabelWidth(Graphics2D g2, 
898            TickUnit unit) {
899
900        RectangleInsets tickLabelInsets = getTickLabelInsets();
901        double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight();
902
903        if (isVerticalTickLabels()) {
904            // all tick labels have the same width (equal to the height of the
905            // font)...
906            FontRenderContext frc = g2.getFontRenderContext();
907            LineMetrics lm = getTickLabelFont().getLineMetrics("0", frc);
908            result += lm.getHeight();
909        }
910        else {
911            // look at lower and upper bounds...
912            Range range = getRange();
913            double lower = range.getLowerBound();
914            double upper = range.getUpperBound();
915            AttributedString lowerStr = createTickLabel(lower);
916            AttributedString upperStr = createTickLabel(upper);
917            double w1 = AttrStringUtils.getTextBounds(lowerStr, g2).getWidth();
918            double w2 = AttrStringUtils.getTextBounds(upperStr, g2).getWidth();
919            result += Math.max(w1, w2);
920        }
921        return result;
922    }
923
924    /**
925     * Zooms in on the current range.
926     *
927     * @param lowerPercent  the new lower bound.
928     * @param upperPercent  the new upper bound.
929     */
930    @Override
931    public void zoomRange(double lowerPercent, double upperPercent) {
932        Range range = getRange();
933        double start = range.getLowerBound();
934        double end = range.getUpperBound();
935        double log1 = calculateLog(start);
936        double log2 = calculateLog(end);
937        double length = log2 - log1;
938        Range adjusted;
939        if (isInverted()) {
940            double logA = log1 + length * (1 - upperPercent);
941            double logB = log1 + length * (1 - lowerPercent);
942            adjusted = new Range(calculateValueNoINF(logA), 
943                    calculateValueNoINF(logB));
944        }
945        else {
946            double logA = log1 + length * lowerPercent;
947            double logB = log1 + length * upperPercent;
948            adjusted = new Range(calculateValueNoINF(logA), 
949                    calculateValueNoINF(logB));
950        }
951        setRange(adjusted);
952    }
953
954    /**
955     * Slides the axis range by the specified percentage.
956     *
957     * @param percent  the percentage.
958     *
959     * @since 1.0.13
960     */
961    @Override
962    public void pan(double percent) {
963        Range range = getRange();
964        double lower = range.getLowerBound();
965        double upper = range.getUpperBound();
966        double log1 = calculateLog(lower);
967        double log2 = calculateLog(upper);
968        double length = log2 - log1;
969        double adj = length * percent;
970        log1 = log1 + adj;
971        log2 = log2 + adj;
972        setRange(calculateValueNoINF(log1), calculateValueNoINF(log2));
973    }
974    
975    /**
976     * Increases or decreases the axis range by the specified percentage about
977     * the central value and sends an {@link AxisChangeEvent} to all registered
978     * listeners.
979     * <P>
980     * To double the length of the axis range, use 200% (2.0).
981     * To halve the length of the axis range, use 50% (0.5).
982     *
983     * @param percent  the resize factor.
984     *
985     * @see #resizeRange(double, double)
986     */
987    @Override
988    public void resizeRange(double percent) {
989        Range range = getRange();
990        double logMin = calculateLog(range.getLowerBound());
991        double logMax = calculateLog(range.getUpperBound());
992        double centralValue = calculateValueNoINF((logMin + logMax) / 2.0);
993        resizeRange(percent, centralValue);
994    }
995
996    @Override
997    public void resizeRange(double percent, double anchorValue) {
998        resizeRange2(percent, anchorValue);
999    }
1000
1001    /**
1002     * Resizes the axis length to the specified percentage of the current
1003     * range and sends a change event to all registered listeners.  If 
1004     * {@code percent} is greater than 1.0 (100 percent) then the axis
1005     * range is increased (which has the effect of zooming out), while if the
1006     * {@code percent} is less than 1.0 the axis range is decreased 
1007     * (which has the effect of zooming in).  The resize occurs around an 
1008     * anchor value (which may not be in the center of the axis).  This is used
1009     * to support mouse wheel zooming around an arbitrary point on the plot.
1010     * <br><br>
1011     * This method is overridden to perform the percentage calculations on the
1012     * log values (which are linear for this axis).
1013     * 
1014     * @param percent  the percentage (must be greater than zero).
1015     * @param anchorValue  the anchor value.
1016     */
1017    @Override
1018    public void resizeRange2(double percent, double anchorValue) {
1019        if (percent > 0.0) {
1020            double logAnchorValue = calculateLog(anchorValue);
1021            Range range = getRange();
1022            double logAxisMin = calculateLog(range.getLowerBound());
1023            double logAxisMax = calculateLog(range.getUpperBound());
1024
1025            double left = percent * (logAnchorValue - logAxisMin);
1026            double right = percent * (logAxisMax - logAnchorValue);
1027            
1028            double upperBound = calculateValueNoINF(logAnchorValue + right);
1029            Range adjusted = new Range(calculateValueNoINF(
1030                    logAnchorValue - left), upperBound);
1031            setRange(adjusted);
1032        }
1033        else {
1034            setAutoRange(true);
1035        }
1036    }
1037
1038    /**
1039     * Tests this axis for equality with an arbitrary object.
1040     *
1041     * @param obj  the object ({@code null} permitted).
1042     *
1043     * @return A boolean.
1044     */
1045    @Override
1046    public boolean equals(Object obj) {
1047        if (obj == this) {
1048            return true;
1049        }
1050        if (!(obj instanceof LogAxis)) {
1051            return false;
1052        }
1053        LogAxis that = (LogAxis) obj;
1054        if (this.base != that.base) {
1055            return false;
1056        }
1057        if (!ObjectUtils.equal(this.baseSymbol, that.baseSymbol)) {
1058            return false;
1059        }
1060        if (!this.baseFormatter.equals(that.baseFormatter)) {
1061            return false;
1062        }
1063        if (this.smallestValue != that.smallestValue) {
1064            return false;
1065        }
1066        if (!ObjectUtils.equal(this.numberFormatOverride, 
1067                that.numberFormatOverride)) {
1068            return false;
1069        }
1070        return super.equals(obj);
1071    }
1072
1073    /**
1074     * Returns a hash code for this instance.
1075     *
1076     * @return A hash code.
1077     */
1078    @Override
1079    public int hashCode() {
1080        int result = 193;
1081        long temp = Double.doubleToLongBits(this.base);
1082        result = 37 * result + (int) (temp ^ (temp >>> 32));
1083        temp = Double.doubleToLongBits(this.smallestValue);
1084        result = 37 * result + (int) (temp ^ (temp >>> 32));
1085        if (this.numberFormatOverride != null) {
1086            result = 37 * result + this.numberFormatOverride.hashCode();
1087        }
1088        result = 37 * result + this.tickUnit.hashCode();
1089        return result;
1090    }
1091
1092}