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 * NumberAxis.java 029 * --------------- 030 * (C) Copyright 2000-2020, by Object Refinery Limited and Contributors. 031 * 032 * Original Author: David Gilbert (for Object Refinery Limited); 033 * Contributor(s): Laurence Vanhelsuwe; 034 * Peter Kolb (patches 1934255 and 2603321); 035 * 036 * Changes 037 * ------- 038 * 18-Sep-2001 : Added standard header and fixed DOS encoding problem (DG); 039 * 22-Sep-2001 : Changed setMinimumAxisValue() and setMaximumAxisValue() so 040 * that they clear the autoRange flag (DG); 041 * 27-Nov-2001 : Removed old, redundant code (DG); 042 * 30-Nov-2001 : Added accessor methods for the standard tick units (DG); 043 * 08-Jan-2002 : Added setAxisRange() method (since renamed setRange()) (DG); 044 * 16-Jan-2002 : Added setTickUnit() method. Extended ValueAxis to support an 045 * optional cross-hair (DG); 046 * 08-Feb-2002 : Fixes bug to ensure the autorange is recalculated if the 047 * setAutoRangeIncludesZero flag is changed (DG); 048 * 25-Feb-2002 : Added a new flag autoRangeStickyZero to provide further 049 * control over margins in the auto-range mechanism. Updated 050 * constructors. Updated import statements. Moved the 051 * createStandardTickUnits() method to the TickUnits class (DG); 052 * 19-Apr-2002 : Updated Javadoc comments (DG); 053 * 01-May-2002 : Updated for changes to TickUnit class, removed valueToString() 054 * method (DG); 055 * 25-Jul-2002 : Moved the lower and upper margin attributes, and the 056 * auto-range minimum size, up one level to the ValueAxis 057 * class (DG); 058 * 05-Sep-2002 : Updated constructor to match changes in Axis class (DG); 059 * 01-Oct-2002 : Fixed errors reported by Checkstyle (DG); 060 * 04-Oct-2002 : Moved standardTickUnits from NumberAxis --> ValueAxis (DG); 061 * 24-Oct-2002 : Added a number format override (DG); 062 * 08-Nov-2002 : Moved to new package com.jrefinery.chart.axis (DG); 063 * 19-Nov-2002 : Removed grid settings (now controlled by the plot) (DG); 064 * 14-Jan-2003 : Changed autoRangeMinimumSize from Number --> double, and moved 065 * crosshair settings to the plot classes (DG); 066 * 20-Jan-2003 : Removed the monolithic constructor (DG); 067 * 26-Mar-2003 : Implemented Serializable (DG); 068 * 16-Jul-2003 : Reworked to allow for multiple secondary axes (DG); 069 * 13-Aug-2003 : Implemented Cloneable (DG); 070 * 07-Oct-2003 : Fixed bug (815028) in the auto range calculation (DG); 071 * 29-Oct-2003 : Added workaround for font alignment in PDF output (DG); 072 * 07-Nov-2003 : Modified to use NumberTick class (DG); 073 * 21-Jan-2004 : Renamed translateJava2DToValue --> java2DToValue, and 074 * translateValueToJava2D --> valueToJava2D (DG); 075 * 03-Mar-2004 : Added plotState to draw() method (DG); 076 * 07-Apr-2004 : Changed string width calculation (DG); 077 * 11-Jan-2005 : Removed deprecated methods in preparation for 1.0.0 078 * release (DG); 079 * 28-Mar-2005 : Renamed autoRangeIncludesZero() --> getAutoRangeIncludesZero() 080 * and autoRangeStickyZero() --> getAutoRangeStickyZero() (DG); 081 * 21-Apr-2005 : Removed redundant argument from selectAutoTickUnit() (DG); 082 * 22-Apr-2005 : Renamed refreshHorizontalTicks --> refreshTicksHorizontal 083 * (and likewise the vertical version) for consistency with 084 * other axis classes (DG); 085 * ------------- JFREECHART 1.0.x --------------------------------------------- 086 * 10-Feb-2006 : Added some API doc comments in respect of bug 821046 (DG); 087 * 20-Feb-2006 : Modified equals() method to check rangeType field (fixes bug 088 * 1435461) (DG); 089 * 04-Sep-2006 : Fix auto range calculation for the case where all data values 090 * are constant and large (see bug report 1549218) (DG); 091 * 11-Dec-2006 : Fix bug in auto-tick unit selection with tick format override, 092 * see bug 1608371 (DG); 093 * 22-Mar-2007 : Use new defaultAutoRange attribute (DG); 094 * 25-Sep-2008 : Added minor tick support, see patch 1934255 by Peter Kolb (DG); 095 * 21-Jan-2009 : Default minor tick counts will now come from the tick unit 096 * collection (DG); 097 * 19-Mar-2009 : Added entity support - see patch 2603321 by Peter Kolb (DG); 098 * 02-Jul-2013 : Use ParamChecks (DG); 099 * 01-Aug-2013 : Added attributedLabel override to support superscripts, 100 * subscripts and more (DG); 101 * 18-Jan-2016 : Update auto-tick unit selection to work better for large 102 * values (DG); 103 * 104 */ 105 106package org.jfree.chart.axis; 107 108import java.awt.Font; 109import java.awt.FontMetrics; 110import java.awt.Graphics2D; 111import java.awt.font.FontRenderContext; 112import java.awt.font.LineMetrics; 113import java.awt.geom.Rectangle2D; 114import java.io.Serializable; 115import java.text.DecimalFormat; 116import java.text.NumberFormat; 117import java.util.List; 118import java.util.Locale; 119 120import org.jfree.chart.event.AxisChangeEvent; 121import org.jfree.chart.plot.Plot; 122import org.jfree.chart.plot.PlotRenderingInfo; 123import org.jfree.chart.plot.ValueAxisPlot; 124import org.jfree.chart.ui.RectangleEdge; 125import org.jfree.chart.ui.RectangleInsets; 126import org.jfree.chart.ui.TextAnchor; 127import org.jfree.chart.util.ObjectUtils; 128import org.jfree.chart.util.Args; 129import org.jfree.data.Range; 130import org.jfree.data.RangeType; 131 132/** 133 * An axis for displaying numerical data. 134 * <P> 135 * If the axis is set up to automatically determine its range to fit the data, 136 * you can ensure that the range includes zero (statisticians usually prefer 137 * this) by setting the {@code autoRangeIncludesZero} flag to 138 * {@code true}. 139 * <P> 140 * The {@code NumberAxis} class has a mechanism for automatically 141 * selecting a tick unit that is appropriate for the current axis range. 142 */ 143public class NumberAxis extends ValueAxis implements Cloneable, Serializable { 144 145 /** For serialization. */ 146 private static final long serialVersionUID = 2805933088476185789L; 147 148 /** The default value for the autoRangeIncludesZero flag. */ 149 public static final boolean DEFAULT_AUTO_RANGE_INCLUDES_ZERO = true; 150 151 /** The default value for the autoRangeStickyZero flag. */ 152 public static final boolean DEFAULT_AUTO_RANGE_STICKY_ZERO = true; 153 154 /** The default tick unit. */ 155 public static final NumberTickUnit DEFAULT_TICK_UNIT = new NumberTickUnit( 156 1.0, new DecimalFormat("0")); 157 158 /** The default setting for the vertical tick labels flag. */ 159 public static final boolean DEFAULT_VERTICAL_TICK_LABELS = false; 160 161 /** 162 * The range type (can be used to force the axis to display only positive 163 * values or only negative values). 164 */ 165 private RangeType rangeType; 166 167 /** 168 * A flag that affects the axis range when the range is determined 169 * automatically. If the auto range does NOT include zero and this flag 170 * is TRUE, then the range is changed to include zero. 171 */ 172 private boolean autoRangeIncludesZero; 173 174 /** 175 * A flag that affects the size of the margins added to the axis range when 176 * the range is determined automatically. If the value 0 falls within the 177 * margin and this flag is TRUE, then the margin is truncated at zero. 178 */ 179 private boolean autoRangeStickyZero; 180 181 /** The tick unit for the axis. */ 182 private NumberTickUnit tickUnit; 183 184 /** The override number format. */ 185 private NumberFormat numberFormatOverride; 186 187 /** An optional band for marking regions on the axis. */ 188 private MarkerAxisBand markerBand; 189 190 /** 191 * Default constructor. 192 */ 193 public NumberAxis() { 194 this(null); 195 } 196 197 /** 198 * Constructs a number axis, using default values where necessary. 199 * 200 * @param label the axis label ({@code null} permitted). 201 */ 202 public NumberAxis(String label) { 203 super(label, NumberAxis.createStandardTickUnits()); 204 this.rangeType = RangeType.FULL; 205 this.autoRangeIncludesZero = DEFAULT_AUTO_RANGE_INCLUDES_ZERO; 206 this.autoRangeStickyZero = DEFAULT_AUTO_RANGE_STICKY_ZERO; 207 this.tickUnit = DEFAULT_TICK_UNIT; 208 this.numberFormatOverride = null; 209 this.markerBand = null; 210 } 211 212 /** 213 * Returns the axis range type. 214 * 215 * @return The axis range type (never {@code null}). 216 * 217 * @see #setRangeType(RangeType) 218 */ 219 public RangeType getRangeType() { 220 return this.rangeType; 221 } 222 223 /** 224 * Sets the axis range type. 225 * 226 * @param rangeType the range type ({@code null} not permitted). 227 * 228 * @see #getRangeType() 229 */ 230 public void setRangeType(RangeType rangeType) { 231 Args.nullNotPermitted(rangeType, "rangeType"); 232 this.rangeType = rangeType; 233 notifyListeners(new AxisChangeEvent(this)); 234 } 235 236 /** 237 * Returns the flag that indicates whether or not the automatic axis range 238 * (if indeed it is determined automatically) is forced to include zero. 239 * 240 * @return The flag. 241 */ 242 public boolean getAutoRangeIncludesZero() { 243 return this.autoRangeIncludesZero; 244 } 245 246 /** 247 * Sets the flag that indicates whether or not the axis range, if 248 * automatically calculated, is forced to include zero. 249 * <p> 250 * If the flag is changed to {@code true}, the axis range is 251 * recalculated. 252 * <p> 253 * Any change to the flag will trigger an {@link AxisChangeEvent}. 254 * 255 * @param flag the new value of the flag. 256 * 257 * @see #getAutoRangeIncludesZero() 258 */ 259 public void setAutoRangeIncludesZero(boolean flag) { 260 if (this.autoRangeIncludesZero != flag) { 261 this.autoRangeIncludesZero = flag; 262 if (isAutoRange()) { 263 autoAdjustRange(); 264 } 265 notifyListeners(new AxisChangeEvent(this)); 266 } 267 } 268 269 /** 270 * Returns a flag that affects the auto-range when zero falls outside the 271 * data range but inside the margins defined for the axis. 272 * 273 * @return The flag. 274 * 275 * @see #setAutoRangeStickyZero(boolean) 276 */ 277 public boolean getAutoRangeStickyZero() { 278 return this.autoRangeStickyZero; 279 } 280 281 /** 282 * Sets a flag that affects the auto-range when zero falls outside the data 283 * range but inside the margins defined for the axis. 284 * 285 * @param flag the new flag. 286 * 287 * @see #getAutoRangeStickyZero() 288 */ 289 public void setAutoRangeStickyZero(boolean flag) { 290 if (this.autoRangeStickyZero != flag) { 291 this.autoRangeStickyZero = flag; 292 if (isAutoRange()) { 293 autoAdjustRange(); 294 } 295 notifyListeners(new AxisChangeEvent(this)); 296 } 297 } 298 299 /** 300 * Returns the tick unit for the axis. 301 * <p> 302 * Note: if the {@code autoTickUnitSelection} flag is 303 * {@code true} the tick unit may be changed while the axis is being 304 * drawn, so in that case the return value from this method may be 305 * irrelevant if the method is called before the axis has been drawn. 306 * 307 * @return The tick unit for the axis. 308 * 309 * @see #setTickUnit(NumberTickUnit) 310 * @see ValueAxis#isAutoTickUnitSelection() 311 */ 312 public NumberTickUnit getTickUnit() { 313 return this.tickUnit; 314 } 315 316 /** 317 * Sets the tick unit for the axis and sends an {@link AxisChangeEvent} to 318 * all registered listeners. A side effect of calling this method is that 319 * the "auto-select" feature for tick units is switched off (you can 320 * restore it using the {@link ValueAxis#setAutoTickUnitSelection(boolean)} 321 * method). 322 * 323 * @param unit the new tick unit ({@code null} not permitted). 324 * 325 * @see #getTickUnit() 326 * @see #setTickUnit(NumberTickUnit, boolean, boolean) 327 */ 328 public void setTickUnit(NumberTickUnit unit) { 329 // defer argument checking... 330 setTickUnit(unit, true, true); 331 } 332 333 /** 334 * Sets the tick unit for the axis and, if requested, sends an 335 * {@link AxisChangeEvent} to all registered listeners. In addition, an 336 * option is provided to turn off the "auto-select" feature for tick units 337 * (you can restore it using the 338 * {@link ValueAxis#setAutoTickUnitSelection(boolean)} method). 339 * 340 * @param unit the new tick unit ({@code null} not permitted). 341 * @param notify notify listeners? 342 * @param turnOffAutoSelect turn off the auto-tick selection? 343 */ 344 public void setTickUnit(NumberTickUnit unit, boolean notify, 345 boolean turnOffAutoSelect) { 346 347 Args.nullNotPermitted(unit, "unit"); 348 this.tickUnit = unit; 349 if (turnOffAutoSelect) { 350 setAutoTickUnitSelection(false, false); 351 } 352 if (notify) { 353 notifyListeners(new AxisChangeEvent(this)); 354 } 355 356 } 357 358 /** 359 * Returns the number format override. If this is non-null, then it will 360 * be used to format the numbers on the axis. 361 * 362 * @return The number formatter (possibly {@code null}). 363 * 364 * @see #setNumberFormatOverride(NumberFormat) 365 */ 366 public NumberFormat getNumberFormatOverride() { 367 return this.numberFormatOverride; 368 } 369 370 /** 371 * Sets the number format override. If this is non-null, then it will be 372 * used to format the numbers on the axis. 373 * 374 * @param formatter the number formatter ({@code null} permitted). 375 * 376 * @see #getNumberFormatOverride() 377 */ 378 public void setNumberFormatOverride(NumberFormat formatter) { 379 this.numberFormatOverride = formatter; 380 notifyListeners(new AxisChangeEvent(this)); 381 } 382 383 /** 384 * Returns the (optional) marker band for the axis. 385 * 386 * @return The marker band (possibly {@code null}). 387 * 388 * @see #setMarkerBand(MarkerAxisBand) 389 */ 390 public MarkerAxisBand getMarkerBand() { 391 return this.markerBand; 392 } 393 394 /** 395 * Sets the marker band for the axis. 396 * <P> 397 * The marker band is optional, leave it set to {@code null} if you 398 * don't require it. 399 * 400 * @param band the new band ({@code null} permitted). 401 * 402 * @see #getMarkerBand() 403 */ 404 public void setMarkerBand(MarkerAxisBand band) { 405 this.markerBand = band; 406 notifyListeners(new AxisChangeEvent(this)); 407 } 408 409 /** 410 * Configures the axis to work with the specified plot. If the axis has 411 * auto-scaling, then sets the maximum and minimum values. 412 */ 413 @Override 414 public void configure() { 415 if (isAutoRange()) { 416 autoAdjustRange(); 417 } 418 } 419 420 /** 421 * Rescales the axis to ensure that all data is visible. 422 */ 423 @Override 424 protected void autoAdjustRange() { 425 426 Plot plot = getPlot(); 427 if (plot == null) { 428 return; // no plot, no data 429 } 430 431 if (plot instanceof ValueAxisPlot) { 432 ValueAxisPlot vap = (ValueAxisPlot) plot; 433 434 Range r = vap.getDataRange(this); 435 if (r == null) { 436 r = getDefaultAutoRange(); 437 } 438 439 double upper = r.getUpperBound(); 440 double lower = r.getLowerBound(); 441 if (this.rangeType == RangeType.POSITIVE) { 442 lower = Math.max(0.0, lower); 443 upper = Math.max(0.0, upper); 444 } 445 else if (this.rangeType == RangeType.NEGATIVE) { 446 lower = Math.min(0.0, lower); 447 upper = Math.min(0.0, upper); 448 } 449 450 if (getAutoRangeIncludesZero()) { 451 lower = Math.min(lower, 0.0); 452 upper = Math.max(upper, 0.0); 453 } 454 double range = upper - lower; 455 456 // if fixed auto range, then derive lower bound... 457 double fixedAutoRange = getFixedAutoRange(); 458 if (fixedAutoRange > 0.0) { 459 lower = upper - fixedAutoRange; 460 } 461 else { 462 // ensure the autorange is at least <minRange> in size... 463 double minRange = getAutoRangeMinimumSize(); 464 if (range < minRange) { 465 double expand = (minRange - range) / 2; 466 upper = upper + expand; 467 lower = lower - expand; 468 if (lower == upper) { // see bug report 1549218 469 double adjust = Math.abs(lower) / 10.0; 470 lower = lower - adjust; 471 upper = upper + adjust; 472 } 473 if (this.rangeType == RangeType.POSITIVE) { 474 if (lower < 0.0) { 475 upper = upper - lower; 476 lower = 0.0; 477 } 478 } 479 else if (this.rangeType == RangeType.NEGATIVE) { 480 if (upper > 0.0) { 481 lower = lower - upper; 482 upper = 0.0; 483 } 484 } 485 } 486 487 if (getAutoRangeStickyZero()) { 488 if (upper <= 0.0) { 489 upper = Math.min(0.0, upper + getUpperMargin() * range); 490 } 491 else { 492 upper = upper + getUpperMargin() * range; 493 } 494 if (lower >= 0.0) { 495 lower = Math.max(0.0, lower - getLowerMargin() * range); 496 } 497 else { 498 lower = lower - getLowerMargin() * range; 499 } 500 } 501 else { 502 upper = upper + getUpperMargin() * range; 503 lower = lower - getLowerMargin() * range; 504 } 505 } 506 507 setRange(new Range(lower, upper), false, false); 508 } 509 510 } 511 512 /** 513 * Converts a data value to a coordinate in Java2D space, assuming that the 514 * axis runs along one edge of the specified dataArea. 515 * <p> 516 * Note that it is possible for the coordinate to fall outside the plotArea. 517 * 518 * @param value the data value. 519 * @param area the area for plotting the data. 520 * @param edge the axis location. 521 * 522 * @return The Java2D coordinate. 523 * 524 * @see #java2DToValue(double, Rectangle2D, RectangleEdge) 525 */ 526 @Override 527 public double valueToJava2D(double value, Rectangle2D area, 528 RectangleEdge edge) { 529 530 Range range = getRange(); 531 double axisMin = range.getLowerBound(); 532 double axisMax = range.getUpperBound(); 533 534 double min = 0.0; 535 double max = 0.0; 536 if (RectangleEdge.isTopOrBottom(edge)) { 537 min = area.getX(); 538 max = area.getMaxX(); 539 } 540 else if (RectangleEdge.isLeftOrRight(edge)) { 541 max = area.getMinY(); 542 min = area.getMaxY(); 543 } 544 if (isInverted()) { 545 return max 546 - ((value - axisMin) / (axisMax - axisMin)) * (max - min); 547 } 548 else { 549 return min 550 + ((value - axisMin) / (axisMax - axisMin)) * (max - min); 551 } 552 553 } 554 555 /** 556 * Converts a coordinate in Java2D space to the corresponding data value, 557 * assuming that the axis runs along one edge of the specified dataArea. 558 * 559 * @param java2DValue the coordinate in Java2D space. 560 * @param area the area in which the data is plotted. 561 * @param edge the location. 562 * 563 * @return The data value. 564 * 565 * @see #valueToJava2D(double, Rectangle2D, RectangleEdge) 566 */ 567 @Override 568 public double java2DToValue(double java2DValue, Rectangle2D area, 569 RectangleEdge edge) { 570 571 Range range = getRange(); 572 double axisMin = range.getLowerBound(); 573 double axisMax = range.getUpperBound(); 574 575 double min = 0.0; 576 double max = 0.0; 577 if (RectangleEdge.isTopOrBottom(edge)) { 578 min = area.getX(); 579 max = area.getMaxX(); 580 } 581 else if (RectangleEdge.isLeftOrRight(edge)) { 582 min = area.getMaxY(); 583 max = area.getY(); 584 } 585 if (isInverted()) { 586 return axisMax 587 - (java2DValue - min) / (max - min) * (axisMax - axisMin); 588 } 589 else { 590 return axisMin 591 + (java2DValue - min) / (max - min) * (axisMax - axisMin); 592 } 593 594 } 595 596 /** 597 * Calculates the value of the lowest visible tick on the axis. 598 * 599 * @return The value of the lowest visible tick on the axis. 600 * 601 * @see #calculateHighestVisibleTickValue() 602 */ 603 protected double calculateLowestVisibleTickValue() { 604 double unit = getTickUnit().getSize(); 605 double index = Math.ceil(getRange().getLowerBound() / unit); 606 return index * unit; 607 } 608 609 /** 610 * Calculates the value of the highest visible tick on the axis. 611 * 612 * @return The value of the highest visible tick on the axis. 613 * 614 * @see #calculateLowestVisibleTickValue() 615 */ 616 protected double calculateHighestVisibleTickValue() { 617 double unit = getTickUnit().getSize(); 618 double index = Math.floor(getRange().getUpperBound() / unit); 619 return index * unit; 620 } 621 622 /** 623 * Calculates the number of visible ticks. 624 * 625 * @return The number of visible ticks on the axis. 626 */ 627 protected int calculateVisibleTickCount() { 628 double unit = getTickUnit().getSize(); 629 Range range = getRange(); 630 return (int) (Math.floor(range.getUpperBound() / unit) 631 - Math.ceil(range.getLowerBound() / unit) + 1); 632 } 633 634 /** 635 * Draws the axis on a Java 2D graphics device (such as the screen or a 636 * printer). 637 * 638 * @param g2 the graphics device ({@code null} not permitted). 639 * @param cursor the cursor location. 640 * @param plotArea the area within which the axes and data should be drawn 641 * ({@code null} not permitted). 642 * @param dataArea the area within which the data should be drawn 643 * ({@code null} not permitted). 644 * @param edge the location of the axis ({@code null} not permitted). 645 * @param plotState collects information about the plot 646 * ({@code null} permitted). 647 * 648 * @return The axis state (never {@code null}). 649 */ 650 @Override 651 public AxisState draw(Graphics2D g2, double cursor, Rectangle2D plotArea, 652 Rectangle2D dataArea, RectangleEdge edge, 653 PlotRenderingInfo plotState) { 654 655 AxisState state; 656 // if the axis is not visible, don't draw it... 657 if (!isVisible()) { 658 state = new AxisState(cursor); 659 // even though the axis is not visible, we need ticks for the 660 // gridlines... 661 List ticks = refreshTicks(g2, state, dataArea, edge); 662 state.setTicks(ticks); 663 return state; 664 } 665 666 // draw the tick marks and labels... 667 state = drawTickMarksAndLabels(g2, cursor, plotArea, dataArea, edge); 668 669 if (getAttributedLabel() != null) { 670 state = drawAttributedLabel(getAttributedLabel(), g2, plotArea, 671 dataArea, edge, state); 672 673 } else { 674 state = drawLabel(getLabel(), g2, plotArea, dataArea, edge, state); 675 } 676 createAndAddEntity(cursor, state, dataArea, edge, plotState); 677 return state; 678 679 } 680 681 /** 682 * Creates the standard tick units. 683 * <P> 684 * If you don't like these defaults, create your own instance of TickUnits 685 * and then pass it to the setStandardTickUnits() method in the 686 * NumberAxis class. 687 * 688 * @return The standard tick units. 689 * 690 * @see #setStandardTickUnits(TickUnitSource) 691 * @see #createIntegerTickUnits() 692 */ 693 public static TickUnitSource createStandardTickUnits() { 694 return new NumberTickUnitSource(); 695 } 696 697 /** 698 * Returns a collection of tick units for integer values. 699 * 700 * @return A collection of tick units for integer values. 701 * 702 * @see #setStandardTickUnits(TickUnitSource) 703 * @see #createStandardTickUnits() 704 */ 705 public static TickUnitSource createIntegerTickUnits() { 706 return new NumberTickUnitSource(true); 707 } 708 709 /** 710 * Creates a collection of standard tick units. The supplied locale is 711 * used to create the number formatter (a localised instance of 712 * {@code NumberFormat}). 713 * <P> 714 * If you don't like these defaults, create your own instance of 715 * {@link TickUnits} and then pass it to the 716 * {@code setStandardTickUnits()} method. 717 * 718 * @param locale the locale. 719 * 720 * @return A tick unit collection. 721 * 722 * @see #setStandardTickUnits(TickUnitSource) 723 */ 724 public static TickUnitSource createStandardTickUnits(Locale locale) { 725 NumberFormat numberFormat = NumberFormat.getNumberInstance(locale); 726 return new NumberTickUnitSource(false, numberFormat); 727 } 728 729 /** 730 * Returns a collection of tick units for integer values. 731 * Uses a given Locale to create the DecimalFormats. 732 * 733 * @param locale the locale to use to represent Numbers. 734 * 735 * @return A collection of tick units for integer values. 736 * 737 * @see #setStandardTickUnits(TickUnitSource) 738 */ 739 public static TickUnitSource createIntegerTickUnits(Locale locale) { 740 NumberFormat numberFormat = NumberFormat.getNumberInstance(locale); 741 return new NumberTickUnitSource(true, numberFormat); 742 } 743 744 /** 745 * Estimates the maximum tick label height. 746 * 747 * @param g2 the graphics device. 748 * 749 * @return The maximum height. 750 */ 751 protected double estimateMaximumTickLabelHeight(Graphics2D g2) { 752 RectangleInsets tickLabelInsets = getTickLabelInsets(); 753 double result = tickLabelInsets.getTop() + tickLabelInsets.getBottom(); 754 755 Font tickLabelFont = getTickLabelFont(); 756 FontRenderContext frc = g2.getFontRenderContext(); 757 result += tickLabelFont.getLineMetrics("123", frc).getHeight(); 758 return result; 759 } 760 761 /** 762 * Estimates the maximum width of the tick labels, assuming the specified 763 * tick unit is used. 764 * <P> 765 * Rather than computing the string bounds of every tick on the axis, we 766 * just look at two values: the lower bound and the upper bound for the 767 * axis. These two values will usually be representative. 768 * 769 * @param g2 the graphics device. 770 * @param unit the tick unit to use for calculation. 771 * 772 * @return The estimated maximum width of the tick labels. 773 */ 774 protected double estimateMaximumTickLabelWidth(Graphics2D g2, 775 TickUnit unit) { 776 777 RectangleInsets tickLabelInsets = getTickLabelInsets(); 778 double result = tickLabelInsets.getLeft() + tickLabelInsets.getRight(); 779 780 if (isVerticalTickLabels()) { 781 // all tick labels have the same width (equal to the height of the 782 // font)... 783 FontRenderContext frc = g2.getFontRenderContext(); 784 LineMetrics lm = getTickLabelFont().getLineMetrics("0", frc); 785 result += lm.getHeight(); 786 } 787 else { 788 // look at lower and upper bounds... 789 FontMetrics fm = g2.getFontMetrics(getTickLabelFont()); 790 Range range = getRange(); 791 double lower = range.getLowerBound(); 792 double upper = range.getUpperBound(); 793 String lowerStr, upperStr; 794 NumberFormat formatter = getNumberFormatOverride(); 795 if (formatter != null) { 796 lowerStr = formatter.format(lower); 797 upperStr = formatter.format(upper); 798 } 799 else { 800 lowerStr = unit.valueToString(lower); 801 upperStr = unit.valueToString(upper); 802 } 803 double w1 = fm.stringWidth(lowerStr); 804 double w2 = fm.stringWidth(upperStr); 805 result += Math.max(w1, w2); 806 } 807 808 return result; 809 810 } 811 812 /** 813 * Selects an appropriate tick value for the axis. The strategy is to 814 * display as many ticks as possible (selected from an array of 'standard' 815 * tick units) without the labels overlapping. 816 * 817 * @param g2 the graphics device. 818 * @param dataArea the area defined by the axes. 819 * @param edge the axis location. 820 */ 821 protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea, 822 RectangleEdge edge) { 823 824 if (RectangleEdge.isTopOrBottom(edge)) { 825 selectHorizontalAutoTickUnit(g2, dataArea, edge); 826 } 827 else if (RectangleEdge.isLeftOrRight(edge)) { 828 selectVerticalAutoTickUnit(g2, dataArea, edge); 829 } 830 831 } 832 833 /** 834 * Selects an appropriate tick value for the axis. The strategy is to 835 * display as many ticks as possible (selected from an array of 'standard' 836 * tick units) without the labels overlapping. 837 * 838 * @param g2 the graphics device. 839 * @param dataArea the area defined by the axes. 840 * @param edge the axis location. 841 */ 842 protected void selectHorizontalAutoTickUnit(Graphics2D g2, 843 Rectangle2D dataArea, RectangleEdge edge) { 844 845 TickUnit unit = getTickUnit(); 846 TickUnitSource tickUnitSource = getStandardTickUnits(); 847 848 // we should start with the current tick unit if it gives a count in 849 // the range 3 to 40 otherwise estimate one that will give a count <= 10 850 double length = getRange().getLength(); 851 int count = (int) (length / unit.getSize()); 852 if (count < 3 || count > 40) { 853 unit = tickUnitSource.getCeilingTickUnit(length / 10); 854 } 855 856 // now consider the label size relative to the width of the tick unit 857 // and make a guess at the ideal size 858 TickUnit unit1 = tickUnitSource.getCeilingTickUnit(unit); 859 double tickLabelWidth = estimateMaximumTickLabelWidth(g2, unit1); 860 double unit1Width = lengthToJava2D(unit1.getSize(), dataArea, edge); 861 NumberTickUnit unit2 = (NumberTickUnit) unit1; 862 double guess = (tickLabelWidth / unit1Width) * unit1.getSize(); 863 864 // due to limitations of double precision, when you zoom very far into 865 // a chart, eventually the visible axis range will get reported as 866 // having length 0, and then 'guess' above will be infinite ... in that 867 // case we'll just stick with the tick unit we have, it's better than 868 // throwing an exception 869 // https://github.com/jfree/jfreechart/issues/64 870 if (Double.isFinite(guess)) { 871 unit2 = (NumberTickUnit) tickUnitSource.getCeilingTickUnit(guess); 872 double unit2Width = lengthToJava2D(unit2.getSize(), dataArea, edge); 873 tickLabelWidth = estimateMaximumTickLabelWidth(g2, unit2); 874 if (tickLabelWidth > unit2Width) { 875 unit2 = (NumberTickUnit) tickUnitSource.getLargerTickUnit(unit2); 876 } 877 } 878 setTickUnit(unit2, false, false); 879 } 880 881 /** 882 * Selects an appropriate tick value for the axis. The strategy is to 883 * display as many ticks as possible (selected from an array of 'standard' 884 * tick units) without the labels overlapping. 885 * 886 * @param g2 the graphics device. 887 * @param dataArea the area in which the plot should be drawn. 888 * @param edge the axis location. 889 */ 890 protected void selectVerticalAutoTickUnit(Graphics2D g2, 891 Rectangle2D dataArea, RectangleEdge edge) { 892 893 double tickLabelHeight = estimateMaximumTickLabelHeight(g2); 894 895 // start with the current tick unit... 896 TickUnitSource tickUnits = getStandardTickUnits(); 897 TickUnit unit1 = tickUnits.getCeilingTickUnit(getTickUnit()); 898 double unitHeight = lengthToJava2D(unit1.getSize(), dataArea, edge); 899 double guess; 900 if (unitHeight > 0) { // then extrapolate... 901 guess = (tickLabelHeight / unitHeight) * unit1.getSize(); 902 } else { 903 guess = getRange().getLength() / 20.0; 904 } 905 NumberTickUnit unit2 = (NumberTickUnit) tickUnits.getCeilingTickUnit( 906 guess); 907 double unit2Height = lengthToJava2D(unit2.getSize(), dataArea, edge); 908 909 tickLabelHeight = estimateMaximumTickLabelHeight(g2); 910 if (tickLabelHeight > unit2Height) { 911 unit2 = (NumberTickUnit) tickUnits.getLargerTickUnit(unit2); 912 } 913 setTickUnit(unit2, false, false); 914 915 } 916 917 /** 918 * Calculates the positions of the tick labels for the axis, storing the 919 * results in the tick label list (ready for drawing). 920 * 921 * @param g2 the graphics device. 922 * @param state the axis state. 923 * @param dataArea the area in which the plot should be drawn. 924 * @param edge the location of the axis. 925 * 926 * @return A list of ticks. 927 */ 928 @Override 929 public List refreshTicks(Graphics2D g2, AxisState state, 930 Rectangle2D dataArea, RectangleEdge edge) { 931 932 List result = new java.util.ArrayList(); 933 if (RectangleEdge.isTopOrBottom(edge)) { 934 result = refreshTicksHorizontal(g2, dataArea, edge); 935 } 936 else if (RectangleEdge.isLeftOrRight(edge)) { 937 result = refreshTicksVertical(g2, dataArea, edge); 938 } 939 return result; 940 941 } 942 943 /** 944 * Calculates the positions of the tick labels for the axis, storing the 945 * results in the tick label list (ready for drawing). 946 * 947 * @param g2 the graphics device. 948 * @param dataArea the area in which the data should be drawn. 949 * @param edge the location of the axis. 950 * 951 * @return A list of ticks. 952 */ 953 protected List refreshTicksHorizontal(Graphics2D g2, 954 Rectangle2D dataArea, RectangleEdge edge) { 955 956 List result = new java.util.ArrayList(); 957 958 Font tickLabelFont = getTickLabelFont(); 959 g2.setFont(tickLabelFont); 960 961 if (isAutoTickUnitSelection()) { 962 selectAutoTickUnit(g2, dataArea, edge); 963 } 964 965 TickUnit tu = getTickUnit(); 966 double size = tu.getSize(); 967 int count = calculateVisibleTickCount(); 968 double lowestTickValue = calculateLowestVisibleTickValue(); 969 970 if (count <= ValueAxis.MAXIMUM_TICK_COUNT) { 971 int minorTickSpaces = getMinorTickCount(); 972 if (minorTickSpaces <= 0) { 973 minorTickSpaces = tu.getMinorTickCount(); 974 } 975 for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) { 976 double minorTickValue = lowestTickValue 977 - size * minorTick / minorTickSpaces; 978 if (getRange().contains(minorTickValue)) { 979 result.add(new NumberTick(TickType.MINOR, minorTickValue, 980 "", TextAnchor.TOP_CENTER, TextAnchor.CENTER, 981 0.0)); 982 } 983 } 984 for (int i = 0; i < count; i++) { 985 double currentTickValue = lowestTickValue + (i * size); 986 String tickLabel; 987 NumberFormat formatter = getNumberFormatOverride(); 988 if (formatter != null) { 989 tickLabel = formatter.format(currentTickValue); 990 } 991 else { 992 tickLabel = getTickUnit().valueToString(currentTickValue); 993 } 994 TextAnchor anchor, rotationAnchor; 995 double angle = 0.0; 996 if (isVerticalTickLabels()) { 997 anchor = TextAnchor.CENTER_RIGHT; 998 rotationAnchor = TextAnchor.CENTER_RIGHT; 999 if (edge == RectangleEdge.TOP) { 1000 angle = Math.PI / 2.0; 1001 } 1002 else { 1003 angle = -Math.PI / 2.0; 1004 } 1005 } 1006 else { 1007 if (edge == RectangleEdge.TOP) { 1008 anchor = TextAnchor.BOTTOM_CENTER; 1009 rotationAnchor = TextAnchor.BOTTOM_CENTER; 1010 } 1011 else { 1012 anchor = TextAnchor.TOP_CENTER; 1013 rotationAnchor = TextAnchor.TOP_CENTER; 1014 } 1015 } 1016 1017 Tick tick = new NumberTick(currentTickValue, tickLabel, anchor, 1018 rotationAnchor, angle); 1019 result.add(tick); 1020 double nextTickValue = lowestTickValue + ((i + 1) * size); 1021 for (int minorTick = 1; minorTick < minorTickSpaces; 1022 minorTick++) { 1023 double minorTickValue = currentTickValue 1024 + (nextTickValue - currentTickValue) 1025 * minorTick / minorTickSpaces; 1026 if (getRange().contains(minorTickValue)) { 1027 result.add(new NumberTick(TickType.MINOR, 1028 minorTickValue, "", TextAnchor.TOP_CENTER, 1029 TextAnchor.CENTER, 0.0)); 1030 } 1031 } 1032 } 1033 } 1034 return result; 1035 1036 } 1037 1038 /** 1039 * Calculates the positions of the tick labels for the axis, storing the 1040 * results in the tick label list (ready for drawing). 1041 * 1042 * @param g2 the graphics device. 1043 * @param dataArea the area in which the plot should be drawn. 1044 * @param edge the location of the axis. 1045 * 1046 * @return A list of ticks. 1047 */ 1048 protected List refreshTicksVertical(Graphics2D g2, 1049 Rectangle2D dataArea, RectangleEdge edge) { 1050 1051 List result = new java.util.ArrayList(); 1052 result.clear(); 1053 1054 Font tickLabelFont = getTickLabelFont(); 1055 g2.setFont(tickLabelFont); 1056 if (isAutoTickUnitSelection()) { 1057 selectAutoTickUnit(g2, dataArea, edge); 1058 } 1059 1060 TickUnit tu = getTickUnit(); 1061 double size = tu.getSize(); 1062 int count = calculateVisibleTickCount(); 1063 double lowestTickValue = calculateLowestVisibleTickValue(); 1064 1065 if (count <= ValueAxis.MAXIMUM_TICK_COUNT) { 1066 int minorTickSpaces = getMinorTickCount(); 1067 if (minorTickSpaces <= 0) { 1068 minorTickSpaces = tu.getMinorTickCount(); 1069 } 1070 for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) { 1071 double minorTickValue = lowestTickValue 1072 - size * minorTick / minorTickSpaces; 1073 if (getRange().contains(minorTickValue)) { 1074 result.add(new NumberTick(TickType.MINOR, minorTickValue, 1075 "", TextAnchor.TOP_CENTER, TextAnchor.CENTER, 1076 0.0)); 1077 } 1078 } 1079 1080 for (int i = 0; i < count; i++) { 1081 double currentTickValue = lowestTickValue + (i * size); 1082 String tickLabel; 1083 NumberFormat formatter = getNumberFormatOverride(); 1084 if (formatter != null) { 1085 tickLabel = formatter.format(currentTickValue); 1086 } 1087 else { 1088 tickLabel = getTickUnit().valueToString(currentTickValue); 1089 } 1090 1091 TextAnchor anchor; 1092 TextAnchor rotationAnchor; 1093 double angle = 0.0; 1094 if (isVerticalTickLabels()) { 1095 if (edge == RectangleEdge.LEFT) { 1096 anchor = TextAnchor.BOTTOM_CENTER; 1097 rotationAnchor = TextAnchor.BOTTOM_CENTER; 1098 angle = -Math.PI / 2.0; 1099 } 1100 else { 1101 anchor = TextAnchor.BOTTOM_CENTER; 1102 rotationAnchor = TextAnchor.BOTTOM_CENTER; 1103 angle = Math.PI / 2.0; 1104 } 1105 } 1106 else { 1107 if (edge == RectangleEdge.LEFT) { 1108 anchor = TextAnchor.CENTER_RIGHT; 1109 rotationAnchor = TextAnchor.CENTER_RIGHT; 1110 } 1111 else { 1112 anchor = TextAnchor.CENTER_LEFT; 1113 rotationAnchor = TextAnchor.CENTER_LEFT; 1114 } 1115 } 1116 1117 Tick tick = new NumberTick(currentTickValue, tickLabel, anchor, 1118 rotationAnchor, angle); 1119 result.add(tick); 1120 1121 double nextTickValue = lowestTickValue + ((i + 1) * size); 1122 for (int minorTick = 1; minorTick < minorTickSpaces; 1123 minorTick++) { 1124 double minorTickValue = currentTickValue 1125 + (nextTickValue - currentTickValue) 1126 * minorTick / minorTickSpaces; 1127 if (getRange().contains(minorTickValue)) { 1128 result.add(new NumberTick(TickType.MINOR, 1129 minorTickValue, "", TextAnchor.TOP_CENTER, 1130 TextAnchor.CENTER, 0.0)); 1131 } 1132 } 1133 } 1134 } 1135 return result; 1136 1137 } 1138 1139 /** 1140 * Returns a clone of the axis. 1141 * 1142 * @return A clone 1143 * 1144 * @throws CloneNotSupportedException if some component of the axis does 1145 * not support cloning. 1146 */ 1147 @Override 1148 public Object clone() throws CloneNotSupportedException { 1149 NumberAxis clone = (NumberAxis) super.clone(); 1150 if (this.numberFormatOverride != null) { 1151 clone.numberFormatOverride 1152 = (NumberFormat) this.numberFormatOverride.clone(); 1153 } 1154 return clone; 1155 } 1156 1157 /** 1158 * Tests the axis for equality with an arbitrary object. 1159 * 1160 * @param obj the object ({@code null} permitted). 1161 * 1162 * @return A boolean. 1163 */ 1164 @Override 1165 public boolean equals(Object obj) { 1166 if (obj == this) { 1167 return true; 1168 } 1169 if (!(obj instanceof NumberAxis)) { 1170 return false; 1171 } 1172 NumberAxis that = (NumberAxis) obj; 1173 if (this.autoRangeIncludesZero != that.autoRangeIncludesZero) { 1174 return false; 1175 } 1176 if (this.autoRangeStickyZero != that.autoRangeStickyZero) { 1177 return false; 1178 } 1179 if (!ObjectUtils.equal(this.tickUnit, that.tickUnit)) { 1180 return false; 1181 } 1182 if (!ObjectUtils.equal(this.numberFormatOverride, 1183 that.numberFormatOverride)) { 1184 return false; 1185 } 1186 if (!this.rangeType.equals(that.rangeType)) { 1187 return false; 1188 } 1189 return super.equals(obj); 1190 } 1191 1192 /** 1193 * Returns a hash code for this object. 1194 * 1195 * @return A hash code. 1196 */ 1197 @Override 1198 public int hashCode() { 1199 return super.hashCode(); 1200 } 1201 1202}