Example usage for org.jfree.chart.axis NumberAxis getTickUnit

List of usage examples for org.jfree.chart.axis NumberAxis getTickUnit

Introduction

In this page you can find the example usage for org.jfree.chart.axis NumberAxis getTickUnit.

Prototype

public NumberTickUnit getTickUnit() 

Source Link

Document

Returns the tick unit for the axis.

Usage

From source file:org.objectweb.proactive.extensions.timitspmd.util.charts.MatrixChart.java

private void buildLegendChart(int nbValues) {
    this.legendValues = new int[nbValues + 1];
    this.legendValues[0] = 0;
    int offset = 255 / nbValues;
    int step = offset;

    if (this.scaleMode == Chart.Scale.LOGARITHMIC) {
        double logStep = (Math.log(this.maxValue) / Math.log(2)) / nbValues;
        for (int i = 1; i < (nbValues + 1); i++) {
            this.legendValues[i] = (int) Math.pow(2, logStep * i);
        }//from  www .  j a va 2 s  .  c o  m
    } else { // Linear scale mode
        for (int i = 1; i < (nbValues + 1); i++) {
            this.legendValues[i] = (step * this.maxValue) / 255;
            step += offset;
        }
    }

    final MatrixSeriesCollection dataset = new MatrixSeriesCollection(this.createLegendDataSet());

    final JFreeChart chart = ChartFactory.createBubbleChart("", "", "", dataset, PlotOrientation.VERTICAL, true,
            true, false);

    chart.setBackgroundPaint(new GradientPaint(0, 0, Color.white, 0, 1000, Color.WHITE));
    chart.removeLegend();

    // Perform customizations starts here ...
    final XYPlot plot1 = chart.getXYPlot();

    plot1.setDomainGridlinesVisible(false);
    plot1.setRangeGridlinesVisible(false);
    plot1.setForegroundAlpha(0.5f);
    plot1.setDomainAxis(new CustomAxis(plot1.getDomainAxis().getLabel()));
    plot1.setRangeAxis(new CustomAxis(plot1.getRangeAxis().getLabel()));

    // Custumize the domain axis ( x )
    final NumberAxis domainAxis = (NumberAxis) plot1.getDomainAxis();
    domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    domainAxis.setRange(-1, 1);
    domainAxis.setVisible(false);

    // Custumize the range axis ( y )
    final NumberAxis rangeAxis = (NumberAxis) plot1.getRangeAxis();
    rangeAxis.setTickUnit(new CustomTickUnit(rangeAxis.getTickUnit().getSize()));
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    rangeAxis.setRange(-1, this.legendValues.length);
    rangeAxis.setTickLabelsVisible(true);
    rangeAxis.setTickMarkInsideLength(4);

    // Create custom renderer
    StandardXYItemRenderer ren = new CustomRenderer(true);
    ren.setSeriesItemLabelPaint(0, Color.BLUE);
    plot1.setRenderer(ren);
    plot1.setRangeAxisLocation(AxisLocation.TOP_OR_RIGHT);

    this.legendChart = chart;
}

From source file:no.met.jtimeseries.marinogram.MarinogramPressurePlot.java

private XYPlot createPlot(TimeZone timezone, boolean plotPressure) {
    ChartPlotter plotter = null;//  www  .  ja  v a2 s.  c o m
    if (plotPressure) {
        plotter = new ChartPlotter();
        // default setting
        plotter.setHeight(this.getHeight());
        plotter.setWidth(this.getWidth());
        plotter.setPlotDefaultProperties("", "");
        NumberPhenomenon pressure = getLocationForecastDataModel()
                .getPhenomenen(PhenomenonName.Pressure.toString(), NumberPhenomenon.class);
        List<Date> shortTermTime = pressure.getTime();
        Color pressureColor = new Color(11, 164, 42);

        PlotStyle.Builder pressureStyleBuilder = new PlotStyle.Builder(
                messages.getString("parameter.pressure") + " (hPa)");
        PlotStyle plotStyle = pressureStyleBuilder.spline(SplineStyle.HYBRID).ticks(4).difference(50.0d)
                .seriesColor(pressureColor).labelColor(pressureColor).build();
        plotter.addLineChart(TimeBase.SECOND, pressure, plotStyle);
        //plotter.formalizeRangeAxisWithMargins(plotter.getRangeAxisIndex() - 1, 950, 1050);

        double tick = (pressure.getMaxValue() - pressure.getMinValue()) / 2;
        tick = Math.ceil(tick / 10) * 10;
        double lowBound = Math.floor(pressure.getMinValue() / (tick)) * (tick);
        lowBound = lowBound - tick / 2;
        double upperBound = lowBound + tick * 4;

        //replicate the range axis 
        NumberAxis referenceAxis = (NumberAxis) plotter.getPlot().getRangeAxis();
        referenceAxis.setTickUnit(new NumberTickUnit(tick));
        referenceAxis.setLowerBound(lowBound);
        referenceAxis.setUpperBound(upperBound);
        NumberAxis numberAxis = new NumberAxis();
        numberAxis.setLabelPaint(pressureColor);
        numberAxis.setTickLabelPaint(referenceAxis.getTickLabelPaint());
        //numberAxis.setLowerMargin(ChartPlotter.LOWER_PLOT_MARGIN);
        numberAxis.setRange(referenceAxis.getLowerBound(), referenceAxis.getUpperBound());
        numberAxis.setTickUnit(referenceAxis.getTickUnit());
        //numberAxis.setRangeWithMargins(950, 1050);
        plotter.getPlot().setRangeAxis(1, numberAxis);

        //first set domain date format and then add hour based domain grid lines
        //TODO: wrap this inside the addHourBasedDomainGridLines for simplicity
        Date minDate = shortTermTime.get(0);
        Date maxDate = shortTermTime.get(shortTermTime.size() >= 48 ? 48 : shortTermTime.size() - 1);
        plotter.setDomainRange(minDate, maxDate);
        plotter.setDomainDateFormat(timezone, "HH");
        plotter.getPlot().setOutlineVisible(true);
        //set domain range after (must) plot all the data
        plotter.addHourBasedDomainGridLines();
        //invisible domain axis
        plotter.getPlot().getDomainAxis().setTickLabelsVisible(false);
        // add markers
        plotter.addDomainMarkers(shortTermTime, timezone, locale);

    }

    return plotter.getPlot();

}

From source file:net.sf.mzmine.modules.visualization.tic.TICPlot.java

@Override
public void actionPerformed(final ActionEvent event) {

    super.actionPerformed(event);

    final String command = event.getActionCommand();

    if ("SHOW_DATA_POINTS".equals(command)) {

        switchDataPointsVisible();/*from   w w w .  j a v a 2  s .co  m*/
    }

    if ("SHOW_ANNOTATIONS".equals(command)) {

        switchItemLabelsVisible();
    }

    if ("SETUP_AXES".equals(command)) {

        new AxesSetupDialog(getXYPlot()).setVisible(true);
    }

    if ("ZOOM_IN".equals(command)) {

        getXYPlot().getDomainAxis().resizeRange(1.0 / ZOOM_FACTOR);
    }

    if ("ZOOM_OUT".equals(command)) {

        getXYPlot().getDomainAxis().resizeRange(ZOOM_FACTOR);
    }

    if ("SET_SAME_RANGE".equals(command)) {

        // Get current axes range.
        final NumberAxis xAxis = (NumberAxis) getXYPlot().getDomainAxis();
        final NumberAxis yAxis = (NumberAxis) getXYPlot().getRangeAxis();
        final double xMin = xAxis.getRange().getLowerBound();
        final double xMax = xAxis.getRange().getUpperBound();
        final double xTick = xAxis.getTickUnit().getSize();
        final double yMin = yAxis.getRange().getLowerBound();
        final double yMax = yAxis.getRange().getUpperBound();
        final double yTick = yAxis.getTickUnit().getSize();

        // Set the range of these frames
        for (final Window frame : JFrame.getWindows()) {
            if (frame instanceof TICVisualizerWindow) {

                final TICVisualizerWindow ticFrame = (TICVisualizerWindow) frame;
                ticFrame.setAxesRange(xMin, xMax, xTick, yMin, yMax, yTick);
            }
        }
    }

    if ("SHOW_SPECTRUM".equals(command)) {

        visualizer.actionPerformed(event);
    }

    if ("SHOW_LEGEND".equals(command)) {

        // Toggle legend visibility.
        final LegendTitle legend = getChart().getLegend();
        legend.setVisible(!legend.isVisible());
    }
}

From source file:net.sf.mzmine.modules.visualization.spectra.SpectraVisualizerWindow.java

public void actionPerformed(ActionEvent event) {

    String command = event.getActionCommand();

    if (command.equals("PEAKLIST_CHANGE")) {

        // If no scan is loaded yet, ignore
        if (currentScan == null)
            return;

        PeakList selectedPeakList = bottomPanel.getSelectedPeakList();
        loadPeaks(selectedPeakList);// ww w  .  j  a  v  a2s  . c o  m

    }

    if (command.equals("PREVIOUS_SCAN")) {

        if (dataFile == null)
            return;

        int msLevel = currentScan.getMSLevel();
        int scanNumbers[] = dataFile.getScanNumbers(msLevel);
        int scanIndex = Arrays.binarySearch(scanNumbers, currentScan.getScanNumber());
        if (scanIndex > 0) {
            final int prevScanIndex = scanNumbers[scanIndex - 1];

            Runnable newThreadRunnable = new Runnable() {

                public void run() {
                    loadRawData(dataFile.getScan(prevScanIndex));
                }

            };

            Thread newThread = new Thread(newThreadRunnable);
            newThread.start();

        }
    }

    if (command.equals("NEXT_SCAN")) {

        if (dataFile == null)
            return;

        int msLevel = currentScan.getMSLevel();
        int scanNumbers[] = dataFile.getScanNumbers(msLevel);
        int scanIndex = Arrays.binarySearch(scanNumbers, currentScan.getScanNumber());

        if (scanIndex < (scanNumbers.length - 1)) {
            final int nextScanIndex = scanNumbers[scanIndex + 1];

            Runnable newThreadRunnable = new Runnable() {

                public void run() {
                    loadRawData(dataFile.getScan(nextScanIndex));
                }

            };

            Thread newThread = new Thread(newThreadRunnable);
            newThread.start();

        }
    }

    if (command.equals("SHOW_MSMS")) {

        String selectedScanString = (String) bottomPanel.getMSMSSelector().getSelectedItem();
        if (selectedScanString == null)
            return;

        int sharpIndex = selectedScanString.indexOf('#');
        int commaIndex = selectedScanString.indexOf(',');
        selectedScanString = selectedScanString.substring(sharpIndex + 1, commaIndex);
        int selectedScan = Integer.valueOf(selectedScanString);

        SpectraVisualizerModule.showNewSpectrumWindow(dataFile, selectedScan);
    }

    if (command.equals("TOGGLE_PLOT_MODE")) {
        if (spectrumPlot.getPlotMode() == PlotMode.CONTINUOUS) {
            spectrumPlot.setPlotMode(PlotMode.CENTROID);
            toolBar.setCentroidButton(false);
        } else {
            spectrumPlot.setPlotMode(PlotMode.CONTINUOUS);
            toolBar.setCentroidButton(true);
        }
    }

    if (command.equals("SHOW_DATA_POINTS")) {
        spectrumPlot.switchDataPointsVisible();
    }

    if (command.equals("SHOW_ANNOTATIONS")) {
        spectrumPlot.switchItemLabelsVisible();
    }

    if (command.equals("SHOW_PICKED_PEAKS")) {
        spectrumPlot.switchPickedPeaksVisible();
    }

    if (command.equals("SHOW_ISOTOPE_PEAKS")) {
        spectrumPlot.switchIsotopePeaksVisible();
    }

    if (command.equals("SETUP_AXES")) {
        AxesSetupDialog dialog = new AxesSetupDialog(spectrumPlot.getXYPlot());
        dialog.setVisible(true);
    }

    if (command.equals("ADD_ISOTOPE_PATTERN")) {

        IsotopePattern newPattern = IsotopePatternCalculator.showIsotopePredictionDialog();

        if (newPattern == null)
            return;

        loadIsotopes(newPattern);

    }

    if ((command.equals("ZOOM_IN")) || (command.equals("ZOOM_IN_BOTH_COMMAND"))) {
        spectrumPlot.getXYPlot().getDomainAxis().resizeRange(1 / zoomCoefficient);
    }

    if ((command.equals("ZOOM_OUT")) || (command.equals("ZOOM_OUT_BOTH_COMMAND"))) {
        spectrumPlot.getXYPlot().getDomainAxis().resizeRange(zoomCoefficient);
    }

    if (command.equals("SET_SAME_RANGE")) {

        // Get current axes range
        NumberAxis xAxis = (NumberAxis) spectrumPlot.getXYPlot().getDomainAxis();
        NumberAxis yAxis = (NumberAxis) spectrumPlot.getXYPlot().getRangeAxis();
        double xMin = (double) xAxis.getRange().getLowerBound();
        double xMax = (double) xAxis.getRange().getUpperBound();
        double xTick = (double) xAxis.getTickUnit().getSize();
        double yMin = (double) yAxis.getRange().getLowerBound();
        double yMax = (double) yAxis.getRange().getUpperBound();
        double yTick = (double) yAxis.getTickUnit().getSize();

        // Get all frames of my class
        Window spectraFrames[] = JFrame.getWindows();

        // Set the range of these frames
        for (Window frame : spectraFrames) {
            if (!(frame instanceof SpectraVisualizerWindow))
                continue;
            SpectraVisualizerWindow spectraFrame = (SpectraVisualizerWindow) frame;
            spectraFrame.setAxesRange(xMin, xMax, xTick, yMin, yMax, yTick);
        }

    }

}

From source file:no.met.jtimeseries.MeteogramWrapper.java

/**
 * Reset bound when both air temperature and dew point temperature are shown
 * @param model/* ww  w. j a  va2 s . co m*/
 * @param plotter
 */
private void resetBoundForTemperature(GenericDataModel model, ChartPlotter plotter) {
    NumberPhenomenon temperature = model.getNumberPhenomenon(PhenomenonName.AirTemperature.toString());
    NumberPhenomenon dewtemperature = model.getNumberPhenomenon(PhenomenonName.dewPointTemperature.toString());
    double minValue = temperature.getMinValue() <= dewtemperature.getMinValue() ? temperature.getMinValue()
            : dewtemperature.getMinValue();
    double maxValue = temperature.getMaxValue() >= dewtemperature.getMaxValue() ? temperature.getMaxValue()
            : dewtemperature.getMaxValue();

    NumberAxis numberAxis1 = (NumberAxis) plotter.getPlot().getRangeAxis(plotter.getPlotIndex() - 2);
    numberAxis1.setLabel(messages.getString("parameter.temperature"));
    ChartPlotter.setAxisBound(numberAxis1, maxValue, minValue, 8, BACKGROUND_LINES);

    NumberAxis numberAxis2 = (NumberAxis) plotter.getPlot().getRangeAxis(plotter.getPlotIndex() - 1);
    numberAxis2.setLabel(messages.getString("parameter.temperature"));
    numberAxis2.setUpperBound(numberAxis1.getUpperBound());
    numberAxis2.setLowerBound(numberAxis1.getLowerBound());
    numberAxis2.setTickUnit(numberAxis1.getTickUnit());
    numberAxis2.setVisible(false);

    //Add labels on the curves
    NumberValueItem airItem = (NumberValueItem) temperature.getItems().get(0);
    NumberValueItem dewpointItem = (NumberValueItem) dewtemperature.getItems().get(0);

    plotter.getPlot().getRenderer()
            .addAnnotation(ChartPlotter.createTextAnnotation(messages.getString("label.air"),
                    temperature.getStartTime().getTime(), airItem.getValue() + 0.1d, TextAnchor.BOTTOM_LEFT,
                    Color.RED), Layer.BACKGROUND);
    plotter.getPlot().getRenderer()
            .addAnnotation(ChartPlotter.createTextAnnotation(messages.getString("label.dewpoint"),
                    dewtemperature.getStartTime().getTime(), dewpointItem.getValue() + 0.1d,
                    TextAnchor.BOTTOM_LEFT, Color.ORANGE), Layer.BACKGROUND);
}

From source file:edu.fullerton.timeseriesapp.TimeSeriesApp.java

public ArrayList<Integer> makePlot(ArrayList<ChanDataBuffer> dbufs, boolean compact) throws WebUtilException {
    int imageId;//w ww. j  a  v  a  2  s. co  m
    try {
        PluginSupport psupport = new PluginSupport();
        String gtitle = psupport.getTitle(dbufs, compact);
        String xAxisLabel = "";
        XYSeriesCollection xyds = new XYSeriesCollection();
        TimeSeriesCollection mtds = new TimeSeriesCollection();

        compact = dbufs.size() > 2 ? false : compact;
        for (ChanDataBuffer dbuf : dbufs) {
            int npts = dbuf.getDataLength();
            int sum = 1;
            if (npts > 2000) {
                sum = npts / 2000;
            }
            String legend = psupport.getLegend(dbuf, compact);
            if (timeAxis.equalsIgnoreCase("utc")) {
                TimeSeries ts = psupport.getTimeSeries(dbuf, legend, sum);
                xAxisLabel = "Time (UTC)";
                mtds.addSeries(ts);
            } else {
                boolean isDt = timeAxis.equalsIgnoreCase("dt");
                XYSeries xys = psupport.addXySeries(dbuf, legend, isDt, sum);
                xAxisLabel = psupport.getxAxisLabel();
                xyds.addSeries(xys);
            }
        }
        Double minx, miny, maxx, maxy;
        Double[] rng = new Double[4];

        if (timeAxis.equalsIgnoreCase("utc")) {
            PluginSupport.getRangeLimits(mtds, rng);
        } else {
            int skip = 0;
            PluginSupport.getRangeLimits(xyds, rng, skip);
        }
        minx = rng[0];
        miny = rng[1];
        maxx = rng[2];
        maxy = rng[3];

        int exp;
        if (timeAxis.equalsIgnoreCase("utc")) {
            exp = PluginSupport.scaleRange(mtds, miny, maxy);
        } else {
            exp = PluginSupport.scaleRange(xyds, miny, maxy);
        }

        ChartPanel cpnl;
        DefaultXYDataset ds = new DefaultXYDataset();
        JFreeChart chart;
        if (timeAxis.equalsIgnoreCase("utc")) {
            chart = ChartFactory.createTimeSeriesChart(gtitle, "Time (UTC)", "Counts", ds, true, true, false);
        } else {
            chart = ChartFactory.createXYLineChart(gtitle, xAxisLabel, "Counts", ds, PlotOrientation.VERTICAL,
                    true, false, false);
        }
        chart.setBackgroundPaint(Color.WHITE);
        chart.setAntiAlias(true);

        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setBackgroundPaint(Color.white);
        plot.setRangeGridlinePaint(Color.LIGHT_GRAY);
        plot.setDomainGridlinePaint(Color.LIGHT_GRAY);

        NumberAxis rangeAxis = new NumberAxis("Counts");
        ScaledAxisNumberFormat sanf = new ScaledAxisNumberFormat();
        sanf.setExp(exp);
        NumberTickUnit tickUnit;
        double plotRange;
        if (maxy != 0 && Math.abs(maxy - miny) < Math.abs(maxy) * 1e-30) {
            // this garbage is to get jFreeChart to always put labels on the Y axis
            double dt = Math.abs(miny) / 10;
            double scaledMin = (miny - dt) * Math.pow(10., exp);
            double scaledMax = (maxy + dt) * Math.pow(10., exp);
            rangeAxis.setRange(scaledMin, scaledMax);
            plotRange = scaledMax - scaledMin;
            rangeAxis.setAutoRange(false);
        } else {
            sanf.setMinMax(miny, maxy);
            plotRange = maxy - miny;
            rangeAxis.setAutoRange(true);
        }
        tickUnit = rangeAxis.getTickUnit();
        double tickSize = tickUnit.getSize();
        int nticks = (int) ((plotRange) / tickSize);
        if (nticks > yTicks) {
            double newTickSize = plotRange / yTicks;
            rangeAxis.setTickUnit(new NumberTickUnit(newTickSize));
        }
        rangeAxis.setNumberFormatOverride(sanf);
        rangeAxis.setAutoRangeIncludesZero(false);
        plot.setRangeAxis(rangeAxis);

        if (timeAxis.equalsIgnoreCase("utc")) {
            plot.setDataset(0, mtds);

        } else {
            plot.setDataset(0, xyds);
        }

        // Set the line thickness
        XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) plot.getRenderer();
        BasicStroke str = new BasicStroke(lineThickness);
        int n = plot.getSeriesCount();
        for (int i = 0; i < n; i++) {
            r.setSeriesStroke(i, str);
        }

        if (compact) {
            chart.removeLegend();
        }
        cpnl = new ChartPanel(chart);
        if (outFilename.isEmpty()) {
            imageId = psupport.saveImageAsPNG(cpnl);
        } else {
            imageId = 0;
            psupport.saveImageAsPdfFile(chart, outFilename);
        }

    } catch (SQLException | NoSuchAlgorithmException | IOException ex) {
        throw new WebUtilException(ex);
    }
    ArrayList<Integer> ret = new ArrayList<>();
    ret.add(imageId);
    return ret;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.monitoring.page.MonitoringPage.java

private ChartImageResource createProgressChart(Map<String, Integer> chartValues, int aMaxValue,
        boolean aIsPercentage) {
    // fill dataset
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    for (String chartValue : chartValues.keySet()) {
        dataset.setValue(chartValues.get(chartValue), "Completion", chartValue);
    }/*ww  w .  jav a 2 s . c om*/
    // create chart
    JFreeChart chart = ChartFactory.createBarChart(null, null, null, dataset, PlotOrientation.HORIZONTAL, false,
            false, false);

    CategoryPlot plot = chart.getCategoryPlot();
    plot.setInsets(new RectangleInsets(UnitType.ABSOLUTE, 0, 20, 0, 20));
    plot.getRangeAxis().setRange(0.0, aMaxValue);
    ((NumberAxis) plot.getRangeAxis()).setNumberFormatOverride(new DecimalFormat("0"));
    // For documents lessan 10, avoid repeating the number of documents such
    // as 0 0 1 1 1
    // NumberTickUnit automatically determin the range
    if (!aIsPercentage && aMaxValue <= 10) {
        TickUnits standardUnits = new TickUnits();
        NumberAxis tick = new NumberAxis();
        tick.setTickUnit(new NumberTickUnit(1));
        standardUnits.add(tick.getTickUnit());
        plot.getRangeAxis().setStandardTickUnits(standardUnits);
    }
    plot.setOutlineVisible(false);
    plot.setBackgroundPaint(null);

    BarRenderer renderer = new BarRenderer();
    renderer.setBarPainter(new StandardBarPainter());
    renderer.setShadowVisible(false);
    // renderer.setGradientPaintTransformer(new
    // StandardGradientPaintTransformer(
    // GradientPaintTransformType.HORIZONTAL));
    renderer.setSeriesPaint(0, Color.BLUE);
    chart.getCategoryPlot().setRenderer(renderer);

    return new ChartImageResource(chart, CHART_WIDTH, 30 + (chartValues.size() * 18));
}

From source file:userinterface.graph.AxisSettings.java

private void updateAxis() {
    /** -- First check whether we still have the right axis object */

    /* If we do not have a logarithmic scale, but the axis settings want one, then change the axis. */
    if (axis instanceof NumberAxis && isLogarithmic()) {
        /** Update xAxis such that other settings can be checked for consistency. */
        PrismLogarithmicAxis newAxis = new PrismLogarithmicAxis(getHeading());

        /** We need to discard all negative and zero values should there be any. */
        /* TODO: Do this in a more elegant way. */
        synchronized (graph.getSeriesLock()) {
            for (Graph.SeriesKey key : graph.getAllSeriesKeys()) {
                XYSeries series = graph.getXYSeries(key);

                if (series instanceof PrismXYSeries) {
                    PrismXYSeries prismSeries = (PrismXYSeries) series;

                    if (isDomain)
                        prismSeries.setLogarithmicDomainAxis(true);
                    else
                        prismSeries.setLogarithmicRangeAxis(true);
                }/*www  .j a  v  a2s  . c  o  m*/
            }
        }

        if (isDomain) {
            this.plot.setDomainAxis(newAxis);
            axis = this.plot.getDomainAxis();
        } else {
            this.plot.setRangeAxis(newAxis);
            axis = this.plot.getRangeAxis();
        }
    }

    /* If we have a logarithmic scale, but the axis settings want a normal scale, then change the axis. */
    if (axis instanceof PrismLogarithmicAxis && !isLogarithmic()) {
        /** Update xAxis such that other settings can be checked for consistency. */
        if (isDomain) {
            this.plot.setDomainAxis(new NumberAxis(getHeading()));
            axis = this.plot.getDomainAxis();
        } else {
            this.plot.setRangeAxis(new NumberAxis(getHeading()));
            axis = this.plot.getRangeAxis();
        }

        /** It could be we discarded some negative and zero values, lets bring them back. */
        synchronized (graph.getSeriesLock()) {
            for (Graph.SeriesKey key : graph.getAllSeriesKeys()) {
                XYSeries series = graph.getXYSeries(key);

                if (series instanceof PrismXYSeries) {
                    PrismXYSeries prismSeries = (PrismXYSeries) series;

                    if (isDomain)
                        prismSeries.setLogarithmicDomainAxis(false);
                    else
                        prismSeries.setLogarithmicRangeAxis(false);
                }
            }
        }
    }

    /** -- Check done, now look for smaller changes. */

    /* If the heading of the axis does not match the heading set in the settings... */
    if (!(axis.getLabel().equals(getHeading()))) {
        axis.setLabel(getHeading());
    }

    /* Update axis heading font if appropriate */
    if (!(axis.getLabelFont().equals(getHeadingFont().f))) {
        axis.setLabelFont(getHeadingFont().f);
    }

    /* Update axis heading colour if appropriate */
    if (!(axis.getLabelPaint().equals(getHeadingFont().c))) {
        axis.setLabelPaint(getHeadingFont().c);
    }

    /* Update axis numbering font if appropriate */
    if (!(axis.getTickLabelFont().equals(getNumberFont().f))) {
        axis.setTickLabelFont(getNumberFont().f);
    }

    /* Update axis numbering colour if appropriate */
    if (!(axis.getTickLabelPaint().equals(getNumberFont().c))) {
        axis.setTickLabelPaint(getNumberFont().c);
    }

    /* Update gridlines if appropriate. */
    if (isDomain && (plot.isDomainGridlinesVisible() != showGrid.getBooleanValue())) {
        plot.setDomainGridlinesVisible(showGrid.getBooleanValue());
    }

    if (!isDomain && (plot.isRangeGridlinesVisible() != showGrid.getBooleanValue())) {
        plot.setRangeGridlinesVisible(showGrid.getBooleanValue());
    }

    /* Update gridline colour if appropriate. */
    if (isDomain && (!plot.getDomainGridlinePaint().equals(gridColour.getColorValue()))) {
        plot.setDomainGridlinePaint(gridColour.getColorValue());
    }

    if (!isDomain && (!plot.getRangeGridlinePaint().equals(gridColour.getColorValue()))) {
        plot.setRangeGridlinePaint(gridColour.getColorValue());
    }

    /** Check properties specific to logarithmic axis. */
    if (axis instanceof PrismLogarithmicAxis) {
        PrismLogarithmicAxis logAxis = (PrismLogarithmicAxis) axis;

        if ((logStyle.getCurrentIndex() == BASE_AND_EXPONENT) != logAxis.isBaseAndExponentFormatOverride()) {
            logAxis.setBaseAndExponentFormatOverride(logStyle.getCurrentIndex() == BASE_AND_EXPONENT);
        }

        if ((logStyle.getCurrentIndex() == VALUES)
                && logAxis.getNumberFormatOverride() != this.valuesFormatter) {
            logAxis.setNumberFormatOverride(this.valuesFormatter);
        }

        /* Switched from auto to manual? */
        if (logAxis.isAutoRange() && !autoScale.getBooleanValue()) {
            Range range = logAxis.getRange();
            logAxis.setAutoRange(false);

            try {
                this.minimumPower.setValue(logAxis.calculateLog(range.getLowerBound()));
                this.maximumPower.setValue(logAxis.calculateLog(range.getUpperBound()));
            } catch (SettingException e) {
                // best effort.
            }
        }

        /* Switched from manual to auto? */
        if (!axis.isAutoRange() && autoScale.getBooleanValue()) {
            axis.setAutoRange(true);
        }

        /* If the log base is wrong. */
        if (logBase.getDoubleValue() != logAxis.getBase()) {
            Range range = axis.getRange();

            logAxis.setBase(logBase.getDoubleValue());

            try {
                this.minimumPower.setValue(logAxis.calculateLog(range.getLowerBound()));
                this.maximumPower.setValue(logAxis.calculateLog(range.getUpperBound()));
            } catch (SettingException e) {
                // best effort
            }

            if (Math.round(logBase.getDoubleValue()) == logBase.getDoubleValue())
                logAxis.setMinorTickCount((int) logBase.getDoubleValue());
            else
                logAxis.setMinorTickCount(1);
        }

        /* If manual, logarithmic, and range does not match our settings, then update */
        if (!axis.isAutoRange()) {
            Range range = logAxis.getRange();

            if (range.getLowerBound() != logAxis.calculateValue(minimumPower.getDoubleValue())
                    || range.getUpperBound() != logAxis.calculateValue(maximumPower.getDoubleValue())) {
                axis.setRange(logAxis.calculateValue(minimumPower.getDoubleValue()),
                        logAxis.calculateValue(maximumPower.getDoubleValue()));
            }
        }
    }

    /** Check properties specific to numeric axis. */
    if (axis instanceof NumberAxis) {
        NumberAxis numAxis = (NumberAxis) axis;

        /* Switched from auto to manual? */
        if (axis.isAutoRange() && !autoScale.getBooleanValue()) {
            Range range = axis.getRange();
            axis.setAutoRange(false);
            axis.setAutoTickUnitSelection(false);

            try {
                this.minValue.setValue(range.getLowerBound());
                this.maxValue.setValue(range.getUpperBound());
                this.gridInterval.setValue(numAxis.getTickUnit().getSize());
            } catch (SettingException e) {
                // best effort.
            }
        }

        /* Switched from manual to auto? */
        if (!axis.isAutoRange() && autoScale.getBooleanValue()) {
            axis.setAutoRange(true);
            axis.setAutoTickUnitSelection(true);
        }

        /* If manual, numeric, and range does not match our settings, then update */
        if (!axis.isAutoRange()) {
            Range range = axis.getRange();

            if (range.getLowerBound() != minValue.getDoubleValue()
                    || range.getUpperBound() != maxValue.getDoubleValue()) {
                axis.setRange(minValue.getDoubleValue(), maxValue.getDoubleValue());
            }

            if (gridInterval.getDoubleValue() != numAxis.getTickUnit().getSize()) {
                // FIXME: With i.e. interval 0.01 it rounds "0.10" to "0.1"
                numAxis.setTickUnit(new NumberTickUnit(gridInterval.getDoubleValue()));
                // Some experimental code to make axis display only odd numbers:
                /*if (axisShouldOnlyShowOdd) numAxis.setNumberFormatOverride(new DecimalFormat()
                { public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {
                      return ((int)number % 2 == 0) ? new StringBuffer("") : super.format(number, toAppendTo, pos);
                } });*/
            }
        }
    }
}

From source file:com.chart.SwingChart.java

/**
 * Set lower and upper limits for an ordinate
 * @param axis Axis to configure//from w  w  w. j a  v a2s .c o  m
 */
void setOrdinateRange(final NumberAxis axis) {
    axis.setAutoRange(false);
    GridPane grid = new GridPane();
    grid.setHgap(10);
    grid.setVgap(10);
    grid.setPadding(new Insets(0, 10, 0, 10));
    final TextField tfMax;
    final TextField tfMin;
    final TextField tfTick;
    final TextField tfFuente;
    grid.add(new Label("Axis"), 0, 0);
    grid.add(new Label(axis.getLabel()), 1, 0);
    grid.add(new Label("Lower"), 0, 1);
    grid.add(tfMin = new TextField(), 1, 1);
    grid.add(new Label("Upper"), 0, 2);
    grid.add(tfMax = new TextField(), 1, 2);
    grid.add(new Label("Space"), 0, 3);
    grid.add(tfTick = new TextField(), 1, 3);

    tfMin.setText(String.valueOf(axis.getLowerBound()));
    tfMax.setText(String.valueOf(axis.getUpperBound()));
    tfTick.setText(String.valueOf(axis.getTickUnit().getSize()));

    new PseudoModalDialog(skeleton, grid, true) {
        @Override
        public boolean validation() {
            axis.setLowerBound(Double.valueOf(tfMin.getText()));
            axis.setUpperBound(Double.valueOf(tfMax.getText()));
            axis.setTickUnit(new NumberTickUnit(Double.valueOf(tfTick.getText())));
            return true;
        }
    }.show();

}

From source file:com.appnativa.rare.ui.chart.jfreechart.ChartHandler.java

public LabelData[] createNonCategoryLabels(ChartDefinition cd, double width, NumberAxis axis, boolean domain,
        double widthDivisor) {
    LabelData[] labels;//w  ww.  j a  va  2  s  .c  om
    double startValue = axis.getLowerBound();
    double endValue = axis.getUpperBound();
    double increment = axis.getTickUnit().getSize();

    if (domain) {
        labels = createLabelData(cd, domain, width, startValue, endValue + increment, increment);

        if (labels.length > 0) {
            labels[labels.length - 1].label = "";
        }
    } else {
        labels = createNumericLabelsData(cd, width, startValue, endValue, increment, domain, widthDivisor);
    }

    return labels;
}