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

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

Introduction

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

Prototype

public Range getRange() 

Source Link

Document

Returns the range for the axis.

Usage

From source file:org.matsim.contrib.analysis.vsp.traveltimedistance.TravelTimeValidationRunner.java

private void writeTravelTimeValidation(String folder, List<CarTrip> trips) {
    BufferedWriter bw = IOUtils.getBufferedWriter(folder + "/validated_trips.csv");
    XYSeriesCollection times = new XYSeriesCollection();
    XYSeriesCollection distances = new XYSeriesCollection();

    XYSeries distancess = new XYSeries("distances", true, true);
    XYSeries timess = new XYSeries("times", true, true);
    times.addSeries(timess);//from   w w  w  . ja  va 2 s .com
    distances.addSeries(distancess);
    try {
        bw.append(
                "agent;departureTime;fromX;fromY;toX;toY;traveltimeActual;traveltimeValidated;traveledDistance;validatedDistance");
        for (CarTrip trip : trips) {
            if (trip.getValidatedTravelTime() != null) {
                bw.newLine();
                bw.append(trip.toString());
                timess.add(trip.getActualTravelTime(), trip.getValidatedTravelTime());
                distancess.add(trip.getTravelledDistance(), trip.getValidatedTravelDistance());
            }
        }

        bw.flush();
        bw.close();
        final JFreeChart chart2 = ChartFactory.createScatterPlot("Travel Times", "Simulated travel time [s]",
                "Validated travel time [s]", times);
        final JFreeChart chart = ChartFactory.createScatterPlot("Travel Distances",
                "Simulated travel distance [m]", "Validated travel distance [m]", distances);

        NumberAxis yAxis = (NumberAxis) ((XYPlot) chart2.getPlot()).getRangeAxis();
        NumberAxis xAxis = (NumberAxis) ((XYPlot) chart2.getPlot()).getDomainAxis();
        NumberAxis yAxisd = (NumberAxis) ((XYPlot) chart.getPlot()).getRangeAxis();
        NumberAxis xAxisd = (NumberAxis) ((XYPlot) chart.getPlot()).getDomainAxis();
        yAxisd.setUpperBound(xAxisd.getUpperBound());
        yAxis.setUpperBound(xAxis.getUpperBound());
        yAxis.setTickUnit(new NumberTickUnit(500));
        xAxis.setTickUnit(new NumberTickUnit(500));

        XYAnnotation diagonal = new XYLineAnnotation(xAxis.getRange().getLowerBound(),
                yAxis.getRange().getLowerBound(), xAxis.getRange().getUpperBound(),
                yAxis.getRange().getUpperBound());
        ((XYPlot) chart2.getPlot()).addAnnotation(diagonal);

        XYAnnotation diagonald = new XYLineAnnotation(xAxisd.getRange().getLowerBound(),
                yAxisd.getRange().getLowerBound(), xAxisd.getRange().getUpperBound(),
                yAxisd.getRange().getUpperBound());
        ((XYPlot) chart.getPlot()).addAnnotation(diagonald);

        ChartUtilities.writeChartAsPNG(new FileOutputStream(folder + "/validated_traveltimes" + ".png"), chart2,
                1500, 1500);
        ChartUtilities.writeChartAsPNG(new FileOutputStream(folder + "/validated_traveldistances.png"), chart,
                1500, 1500);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

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);//from www  . ja  v  a  2  s .  c  om

    }

    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:ucar.unidata.idv.control.chart.ScatterPlotChartWrapper.java

/**
 * Create the charts/*from w w  w.j  av a2s. c om*/
 *
 * @throws RemoteException On badness
 * @throws VisADException On badness
 */
public void loadData() throws VisADException, RemoteException {

    try {
        createChart();
        for (int dataSetIdx = 0; dataSetIdx < plot.getDatasetCount(); dataSetIdx++) {
            XYSeriesCollection dataset = (XYSeriesCollection) plot.getDataset(dataSetIdx);
            dataset.removeAllSeries();
        }
        ((MyScatterPlot) plot).removeAllSeries();
        Hashtable props = new Hashtable();
        props.put(TrackDataSource.PROP_TRACKTYPE, TrackDataSource.ID_TIMETRACE);

        List dataChoiceWrappers = getDataChoiceWrappers();
        int dataSetCnt = 0;
        for (int paramIdx = 0; paramIdx < dataChoiceWrappers.size(); paramIdx += 2) {
            if (paramIdx + 1 >= dataChoiceWrappers.size()) {
                break;
            }
            DataChoiceWrapper wrapper1 = (DataChoiceWrapper) dataChoiceWrappers.get(paramIdx);
            DataChoiceWrapper wrapper2 = (DataChoiceWrapper) dataChoiceWrappers.get(paramIdx + 1);

            DataChoice dataChoice1 = wrapper1.getDataChoice();
            DataChoice dataChoice2 = wrapper2.getDataChoice();

            FlatField data1 = getFlatField((FieldImpl) dataChoice1.getData(null, props));
            FlatField data2 = getFlatField((FieldImpl) dataChoice2.getData(null, props));
            Unit unit1 = ucar.visad.Util.getDefaultRangeUnits((FlatField) data1)[0];
            Unit unit2 = ucar.visad.Util.getDefaultRangeUnits((FlatField) data2)[0];

            NumberAxis rangeAxis = new NumberAxis(wrapper2.getLabel(unit2));
            NumberAxis domainAxis = new NumberAxis(wrapper1.getLabel(unit1));

            domainAxis.setAutoRange(getAutoRange());

            Color c = wrapper1.getColor(paramIdx);
            MyRenderer renderer = new MyRenderer(wrapper1.getLineState().getShape());
            domainAxis.setLabelPaint(c);
            rangeAxis.setLabelPaint(c);
            renderer.setSeriesPaint(0, c);

            double[][] samples1 = data1.getValues(false);
            double[][] samples2 = data2.getValues(false);
            double[] timeValues1 = getTimeValues(samples1, data1);
            double[] timeValues2 = getTimeValues(samples2, data2);
            double[][] values1 = filterData(samples1[0], timeValues1);
            double[][] values2 = filterData(samples2[0], timeValues2);
            if (values1.length > 1) {
                this.timeValues1 = values1[1];
                this.timeValues2 = values2[1];
            }
            double[][] values = { values1[0], values2[0] };
            ((MyScatterPlot) plot).addSeries(values);

            //Add in a dummy dataset
            XYSeriesCollection dataset = new XYSeriesCollection(new XYSeries(""));

            if (!getAutoRange()) {
                NumberAxis oldRangeAxis = (NumberAxis) plot.getRangeAxis(dataSetCnt);
                NumberAxis oldDomainAxis = (NumberAxis) plot.getDomainAxis(dataSetCnt);
                if ((oldRangeAxis != null) && (oldDomainAxis != null)) {
                    rangeAxis.setRange(oldRangeAxis.getRange());
                    domainAxis.setRange(oldDomainAxis.getRange());
                }
            }

            plot.setDataset(dataSetCnt, dataset);
            plot.setRenderer(dataSetCnt, renderer);
            plot.setRangeAxis(dataSetCnt, rangeAxis, false);
            plot.setDomainAxis(dataSetCnt, domainAxis, false);
            plot.mapDatasetToRangeAxis(dataSetCnt, dataSetCnt);
            plot.mapDatasetToDomainAxis(dataSetCnt, dataSetCnt);

            if (!getAutoRange()) {
                rangeAxis.setAutoRange(false);
                domainAxis.setAutoRange(false);
            }

            dataSetCnt++;
        }
    } catch (Exception exc) {
        LogUtil.logException("Error creating data set", exc);
    }

}

From source file:web.diva.server.unused.PCAGenerator.java

public PCAImageResult generateChart(String path, PCAResults pcaResults, int[] subSelectionData, int[] selection,
        boolean zoom, boolean selectAll, String imgName, double w, double h, DivaDataset divaDataset) {
    XYDataset dataset = this.createDataset(pcaResults.getPoints(), subSelectionData, selection, zoom,
            divaDataset);//from w w w.  jav a  2  s .c  o  m
    final JFreeChart chart = ChartFactory.createScatterPlot("", // chart title
            "Principal Component" + (pcaResults.getPcai() + 1), // x axis label
            "Principal Component " + (pcaResults.getPcaii() + 1), // y axis label
            dataset, // data
            PlotOrientation.VERTICAL, false, // include legend
            true, // tooltips
            false // urls
    );
    final XYPlot plot = chart.getXYPlot();
    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainGridlinePaint(Color.WHITE);
    plot.setRangeGridlinePaint(Color.WHITE);
    XYDotRenderer renderer = new XYDotRenderer();
    renderer.setDotHeight(5);
    renderer.setDotWidth(5);

    if (selectAll) {
        int i = 0;
        for (String col : seriesList.keySet()) {
            if (col.equalsIgnoreCase("unGrouped")) {
                col = "#000000";
            }
            renderer.setSeriesPaint(i, imgGenerator.hex2Rgb(col));
            i++;
        }

    } else if (selection == null) {
        renderer.setPaint(Color.LIGHT_GRAY);
        int i = 0;
        for (String col : seriesList.keySet()) {
            if (col.equalsIgnoreCase("unGrouped")) {
                col = "#000000";
            }
            renderer.setSeriesPaint(i, imgGenerator.hex2Rgb(col));
            i++;
        }
    } else {
        int i = 0;
        for (String col : seriesList.keySet()) {
            if (col.equalsIgnoreCase("unGrouped")) {
                renderer.setSeriesPaint(i, Color.LIGHT_GRAY);
            } else {
                renderer.setSeriesPaint(i, imgGenerator.hex2Rgb(col));

            }
            i++;
        }
    }
    plot.setRenderer(renderer);
    plot.setSeriesRenderingOrder(SeriesRenderingOrder.REVERSE);
    NumberAxis xAxis = new NumberAxis("Principal Component" + (pcaResults.getPcai() + 1));
    xAxis.setVerticalTickLabels(true);
    boolean auto = xAxis.getAutoRangeIncludesZero();
    xAxis.setAutoRangeIncludesZero(true ^ auto);
    NumberAxis yAxis = new NumberAxis("Principal Component" + (pcaResults.getPcaii() + 1));
    yAxis.setAutoRangeIncludesZero(true ^ auto);
    yAxis.setTickUnit(new NumberTickUnit(1));
    plot.setDomainAxis(0, xAxis);
    plot.setRangeAxis(0, yAxis);

    double MaxX = xAxis.getRange().getUpperBound();
    double MinX = xAxis.getRange().getLowerBound();
    double MaxY = yAxis.getRange().getUpperBound();
    double MinY = yAxis.getRange().getLowerBound();

    chartRenderingInfo.clear();
    String imgUrl = imgGenerator.saveToFile(chart, w, h, chartRenderingInfo);
    PCAImageResult imgUtilRes = new PCAImageResult();
    imgUtilRes.setImgString(imgUrl);
    imgUtilRes.setDataAreaMaxX(chartRenderingInfo.getPlotInfo().getDataArea().getMaxX());
    imgUtilRes.setDataAreaMaxY(chartRenderingInfo.getPlotInfo().getDataArea().getMaxY());
    imgUtilRes.setDataAreaMinY(chartRenderingInfo.getPlotInfo().getDataArea().getMinY());
    imgUtilRes.setDataAreaMinX(chartRenderingInfo.getPlotInfo().getDataArea().getMinX());
    imgUtilRes.setMaxX(MaxX);
    imgUtilRes.setMaxY(MaxY);
    imgUtilRes.setMinX(MinX);
    imgUtilRes.setMinY(MinY);
    return imgUtilRes;
}

From source file:web.diva.server.model.PCAGenerator.java

public PCAImageResult generateChart(String path, PCAResults pcaResults, int[] subSelectionData, int[] selection,
        boolean zoom, boolean selectAll, String imgName, double w, double h, DivaDataset divaDataset) {
    XYDataset dataset = this.createDataset(pcaResults.getPoints(), subSelectionData, selection, zoom,
            divaDataset);// ww w.j  a va  2 s. co m
    final JFreeChart chart = ChartFactory.createScatterPlot("", // chart title
            "Principal Component" + (pcaResults.getPcai() + 1), // x axis label
            "Principal Component " + (pcaResults.getPcaii() + 1), // y axis label
            dataset, // data
            PlotOrientation.VERTICAL, false, // include legend
            true, // tooltips
            false // urls
    );
    final XYPlot plot = chart.getXYPlot();
    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainGridlinePaint(Color.WHITE);
    plot.setRangeGridlinePaint(Color.WHITE);
    XYDotRenderer renderer = new XYDotRenderer();
    renderer.setDotHeight(5);
    renderer.setDotWidth(5);

    if (selectAll) {
        int i = 0;
        for (String col : seriesList.keySet()) {
            if (col.equalsIgnoreCase("unGrouped")) {
                col = "#000000";
            }
            renderer.setSeriesPaint(i, imgGenerator.hex2Rgb(col));
            i++;
        }

    } else if (selection == null) {
        renderer.setPaint(Color.LIGHT_GRAY);
        int i = 0;
        for (String col : seriesList.keySet()) {
            if (col.equalsIgnoreCase("unGrouped")) {
                col = "#000000";
            }
            renderer.setSeriesPaint(i, imgGenerator.hex2Rgb(col));
            i++;
        }
    } else {
        int i = 0;
        for (String col : seriesList.keySet()) {
            if (col.equalsIgnoreCase("unGrouped")) {
                renderer.setSeriesPaint(i, Color.LIGHT_GRAY);
            } else {
                renderer.setSeriesPaint(i, imgGenerator.hex2Rgb(col));

            }
            i++;
        }
    }
    plot.setRenderer(renderer);
    plot.setSeriesRenderingOrder(SeriesRenderingOrder.REVERSE);
    NumberAxis xAxis = new NumberAxis("Principal Component" + (pcaResults.getPcai() + 1));
    xAxis.setVerticalTickLabels(true);
    boolean auto = xAxis.getAutoRangeIncludesZero();
    xAxis.setAutoRangeIncludesZero(true ^ auto);
    NumberAxis yAxis = new NumberAxis("Principal Component" + (pcaResults.getPcaii() + 1));
    yAxis.setAutoRangeIncludesZero(true ^ auto);
    yAxis.setTickUnit(new NumberTickUnit(1));
    plot.setDomainAxis(0, xAxis);
    plot.setRangeAxis(0, yAxis);

    double MaxX = xAxis.getRange().getUpperBound();
    double MinX = xAxis.getRange().getLowerBound();
    double MaxY = yAxis.getRange().getUpperBound();
    double MinY = yAxis.getRange().getLowerBound();

    chartRenderingInfo.clear();
    String imgUrl = imgGenerator.saveToFile(chart, w, h, path, chartRenderingInfo, imgName);
    PCAImageResult imgUtilRes = new PCAImageResult();
    imgUtilRes.setImgString(imgUrl);
    imgUtilRes.setDataAreaMaxX(chartRenderingInfo.getPlotInfo().getDataArea().getMaxX());
    imgUtilRes.setDataAreaMaxY(chartRenderingInfo.getPlotInfo().getDataArea().getMaxY());
    imgUtilRes.setDataAreaMinY(chartRenderingInfo.getPlotInfo().getDataArea().getMinY());
    imgUtilRes.setDataAreaMinX(chartRenderingInfo.getPlotInfo().getDataArea().getMinX());
    imgUtilRes.setMaxX(MaxX);
    imgUtilRes.setMaxY(MaxY);
    imgUtilRes.setMinX(MinX);
    imgUtilRes.setMinY(MinY);
    return imgUtilRes;
}

From source file:edu.wisc.ssec.mcidasv.control.McIDASVHistogramWrapper.java

/**
 * Assumes that {@code data} has been validated and is okay to actually try
 * loading.// ww  w.  j  a v  a2  s.c o m
 *
 * @param data Data to use in histogram. Cannot be {@code null} or all NaNs.
 *
 * @throws VisADException
 * @throws RemoteException
 */
private void reallyLoadData(FlatField data) throws VisADException, RemoteException {
    createChart();
    List dataChoiceWrappers = getDataChoiceWrappers();

    try {
        clearHistogram();

        Hashtable props = new Hashtable();
        ErrorEstimate[] errOut = new ErrorEstimate[1];
        for (int paramIdx = 0; paramIdx < dataChoiceWrappers.size(); paramIdx++) {
            DataChoiceWrapper wrapper = (DataChoiceWrapper) dataChoiceWrappers.get(paramIdx);

            DataChoice dataChoice = wrapper.getDataChoice();
            props = dataChoice.getProperties();
            Unit defaultUnit = ucar.visad.Util.getDefaultRangeUnits((FlatField) data)[0];
            Unit unit = ((DisplayControlImpl) imageControl).getDisplayUnit();
            double[][] samples = data.getValues(false);
            double[] actualValues = filterData(samples[0], getTimeValues(samples, data))[0];
            if ((defaultUnit != null) && !defaultUnit.equals(unit)) {
                actualValues = Unit.transformUnits(unit, errOut, defaultUnit, null, actualValues);
            }
            final NumberAxis domainAxis = new NumberAxis(wrapper.getLabel(unit));

            domainAxis.setAutoRangeIncludesZero(false);

            XYItemRenderer renderer;
            if (getStacked()) {
                renderer = new StackedXYBarRenderer();
            } else {
                renderer = new XYBarRenderer();
            }
            if ((plot == null) && (chartPanel != null)) {
                plot = chartPanel.getChart().getXYPlot();
            }
            plot.setRenderer(paramIdx, renderer);
            Color c = wrapper.getColor(paramIdx);
            domainAxis.setLabelPaint(c);
            renderer.setSeriesPaint(0, c);

            MyHistogramDataset dataset = new MyHistogramDataset();
            dataset.setType(HistogramType.FREQUENCY);
            dataset.addSeries(dataChoice.getName() + " [" + unit + ']', actualValues, getBins());
            samples = null;
            actualValues = null;
            plot.setDomainAxis(paramIdx, domainAxis, false);
            plot.mapDatasetToDomainAxis(paramIdx, paramIdx);
            plot.setDataset(paramIdx, dataset);

            domainAxis.addChangeListener(new AxisChangeListener() {
                public void axisChanged(AxisChangeEvent ae) {
                    if (!imageControl.isInitDone()) {
                        return;
                    }

                    Range range = domainAxis.getRange();
                    double newLow = Math.floor(range.getLowerBound() + 0.5);
                    double newHigh = Math.floor(range.getUpperBound() + 0.5);
                    double prevLow = getLow();
                    double prevHigh = getHigh();
                    try {
                        ucar.unidata.util.Range newRange;
                        if (prevLow > prevHigh) {
                            newRange = new ucar.unidata.util.Range(newHigh, newLow);
                        } else {
                            newRange = new ucar.unidata.util.Range(newLow, newHigh);
                        }
                        ((DisplayControlImpl) imageControl).setRange(newRange);
                    } catch (Exception e) {
                        logger.error("Cannot change range", e);
                    }
                }
            });

            Range range = domainAxis.getRange();
            low = range.getLowerBound();
            high = range.getUpperBound();
        }

    } catch (Exception exc) {
        System.out.println("Exception exc=" + exc);
        LogUtil.logException("Error creating data set", exc);
    }
}

From source file:ucar.unidata.idv.control.McVHistogramWrapper.java

/**
 * Assumes that {@code data} has been validated and is okay to actually try
 * loading.//from   w  w  w  .j  ava2s  . c  om
 *
 * @param data Data to use in histogram. Cannot be {@code null} or all NaNs.
 *
 * @throws VisADException
 * @throws RemoteException
 */
private void reallyLoadData(FlatField data) throws VisADException, RemoteException {
    createChart();
    List dataChoiceWrappers = getDataChoiceWrappers();

    try {
        clearHistogram();

        ErrorEstimate[] errOut = new ErrorEstimate[1];
        for (int paramIdx = 0; paramIdx < dataChoiceWrappers.size(); paramIdx++) {
            DataChoiceWrapper wrapper = (DataChoiceWrapper) dataChoiceWrappers.get(paramIdx);

            DataChoice dataChoice = wrapper.getDataChoice();
            Unit defaultUnit = ucar.visad.Util.getDefaultRangeUnits((FlatField) data)[0];
            Unit unit = ((DisplayControlImpl) imageControl).getDisplayUnit();
            double[][] samples = data.getValues(false);
            double[] actualValues = filterData(samples[0], getTimeValues(samples, data))[0];
            if ((defaultUnit != null) && !defaultUnit.equals(unit)) {
                actualValues = Unit.transformUnits(unit, errOut, defaultUnit, null, actualValues);
            }
            final NumberAxis domainAxis = new NumberAxis(wrapper.getLabel(unit));

            domainAxis.setAutoRangeIncludesZero(false);

            XYItemRenderer renderer;
            if (getStacked()) {
                renderer = new StackedXYBarRenderer();
            } else {
                renderer = new XYBarRenderer();
            }
            if ((plot == null) && (chartPanel != null)) {
                plot = chartPanel.getChart().getXYPlot();
            }
            plot.setRenderer(paramIdx, renderer);
            Color c = wrapper.getColor(paramIdx);
            domainAxis.setLabelPaint(c);
            renderer.setSeriesPaint(0, c);

            MyHistogramDataset dataset = new MyHistogramDataset();
            dataset.setType(HistogramType.FREQUENCY);
            dataset.addSeries(dataChoice.getName() + " [" + unit + ']', actualValues, getBins());
            samples = null;
            actualValues = null;
            plot.setDomainAxis(paramIdx, domainAxis, false);
            plot.mapDatasetToDomainAxis(paramIdx, paramIdx);
            plot.setDataset(paramIdx, dataset);

            domainAxis.addChangeListener(new AxisChangeListener() {
                public void axisChanged(AxisChangeEvent ae) {
                    if (!imageControl.isInitDone()) {
                        return;
                    }

                    Range range = domainAxis.getRange();
                    double newLow = Math.floor(range.getLowerBound() + 0.5);
                    double newHigh = Math.floor(range.getUpperBound() + 0.5);
                    double prevLow = getLow();
                    double prevHigh = getHigh();
                    try {
                        ucar.unidata.util.Range newRange;
                        if (prevLow > prevHigh) {
                            newRange = new ucar.unidata.util.Range(newHigh, newLow);
                        } else {
                            newRange = new ucar.unidata.util.Range(newLow, newHigh);
                        }
                        ((DisplayControlImpl) imageControl).setRange(newRange);
                    } catch (Exception e) {
                        logger.error("Cannot change range", e);
                    }
                }
            });

            Range range = domainAxis.getRange();
            low = range.getLowerBound();
            high = range.getUpperBound();
        }

    } catch (Exception exc) {
        System.out.println("Exception exc=" + exc);
        LogUtil.logException("Error creating data set", exc);
    }
}

From source file:net.sf.jasperreports.engine.fill.DefaultChartTheme.java

/**
 * For a given axis, adjust the tick unit size, in order to 
 * have a customizable number of ticks on that axis
 *//*from  www.  j  a  va 2s  .com*/
protected void calculateTickUnits(Axis axis, boolean isRangeAxis) {
    Integer tickCount = null;
    Number tickInterval = null;
    boolean axisIntegerUnit = false;

    if (getChart().hasProperties()) {
        String tickCountProperty = null;
        String tickIntervalProperty = null;
        String axisIntegerUnitProperty = null;

        if (isRangeAxis) {
            tickCountProperty = getChart().getPropertiesMap()
                    .getProperty(DefaultChartTheme.PROPERTY_RANGE_AXIS_TICK_COUNT);
            tickIntervalProperty = getChart().getPropertiesMap()
                    .getProperty(DefaultChartTheme.PROPERTY_RANGE_AXIS_TICK_INTERVAL);
            axisIntegerUnitProperty = getChart().getPropertiesMap()
                    .getProperty(DefaultChartTheme.PROPERTY_RANGE_AXIS_INTEGER_UNIT);
        } else {
            tickCountProperty = getChart().getPropertiesMap()
                    .getProperty(DefaultChartTheme.PROPERTY_DOMAIN_AXIS_TICK_COUNT);
            tickIntervalProperty = getChart().getPropertiesMap()
                    .getProperty(DefaultChartTheme.PROPERTY_DOMAIN_AXIS_TICK_INTERVAL);
            axisIntegerUnitProperty = getChart().getPropertiesMap()
                    .getProperty(DefaultChartTheme.PROPERTY_DOMAIN_AXIS_INTEGER_UNIT);
        }
        if (tickCountProperty != null && tickCountProperty.trim().length() > 0) {
            tickCount = Integer.valueOf(tickCountProperty);
        }
        if (tickIntervalProperty != null && tickIntervalProperty.trim().length() > 0) {
            tickInterval = Double.valueOf(tickIntervalProperty);
        }
        if (axisIntegerUnitProperty != null && axisIntegerUnitProperty.trim().length() > 0) {
            axisIntegerUnit = Boolean.valueOf(axisIntegerUnitProperty);
        }
    }

    if (axis instanceof NumberAxis) {
        NumberAxis numberAxis = (NumberAxis) axis;
        int axisRange = (int) numberAxis.getRange().getLength();

        if (axisIntegerUnit) {
            ChartUtil chartUtil = ChartUtil.getInstance(chartContext.getJasperReportsContext());
            numberAxis.setStandardTickUnits(chartUtil.createIntegerTickUnits(getLocale()));
            chartUtil.setAutoTickUnit(numberAxis);
        } else if (axisRange > 0) {
            if (tickInterval != null) {
                if (numberAxis.getNumberFormatOverride() != null) {
                    numberAxis.setTickUnit(new NumberTickUnit(tickInterval.doubleValue(),
                            numberAxis.getNumberFormatOverride()));
                } else {
                    numberAxis.setTickUnit(new NumberTickUnit(tickInterval.doubleValue(),
                            NumberFormat.getNumberInstance(getLocale())));
                }
            } else if (tickCount != null) {
                if (numberAxis.getNumberFormatOverride() != null) {
                    numberAxis.setTickUnit(
                            new NumberTickUnit(axisRange / tickCount, numberAxis.getNumberFormatOverride()));
                } else {
                    numberAxis.setTickUnit(new NumberTickUnit(axisRange / tickCount,
                            NumberFormat.getNumberInstance(getLocale())));
                }
            } else {
                ChartUtil chartUtil = ChartUtil.getInstance(chartContext.getJasperReportsContext());
                numberAxis.setStandardTickUnits(chartUtil.createStandardTickUnits(getLocale()));
                chartUtil.setAutoTickUnit(numberAxis);
            }
        }
    }
    //      else if (axis instanceof DateAxis)
    //      {
    //         DateAxis dateAxis = (DateAxis)axis;
    //         int axisRange = (int)dateAxis.getRange().getLength();
    //         if (dateAxis.getDateFormatOverride() != null)
    //         {
    //            dateAxis.setTickUnit(new DateTickUnit(timePeriodUnit, axisRange/tickCount, dateAxis.getDateFormatOverride()));
    //         }
    //         else
    //         {
    //            dateAxis.setTickUnit(new DateTickUnit(timePeriodUnit, axisRange/tickCount));
    //         }
    //      }
}

From source file:net.sf.fspdfs.chartthemes.simple.SimpleChartTheme.java

/**
 * For a given axis, adjust the tick unit size, in order to 
 * have a customizable number of ticks on that axis
 *//*from   w ww  .  j  a  v a2 s  .c  o m*/
protected void calculateTickUnits(Axis axis, AxisSettings axisSettings, int timePeriodUnit) {
    Integer tickCount = null;
    Number tickInterval = null;

    if (getChart().hasProperties()) {
        String tickCountProperty = null;
        String tickIntervalProperty = null;
        if (axisSettings == getChartThemeSettings().getRangeAxisSettings()) {
            tickCountProperty = getChart().getPropertiesMap()
                    .getProperty(DefaultChartTheme.PROPERTY_RANGE_AXIS_TICK_COUNT);
            tickIntervalProperty = getChart().getPropertiesMap()
                    .getProperty(DefaultChartTheme.PROPERTY_RANGE_AXIS_TICK_INTERVAL);
        } else {
            tickCountProperty = getChart().getPropertiesMap()
                    .getProperty(DefaultChartTheme.PROPERTY_DOMAIN_AXIS_TICK_COUNT);
            tickIntervalProperty = getChart().getPropertiesMap()
                    .getProperty(DefaultChartTheme.PROPERTY_DOMAIN_AXIS_TICK_INTERVAL);
        }
        if (tickCountProperty != null && tickCountProperty.trim().length() > 0) {
            tickCount = Integer.valueOf(tickCountProperty);
        }
        if (tickIntervalProperty != null && tickIntervalProperty.trim().length() > 0) {
            tickInterval = Double.valueOf(tickIntervalProperty);
        }
    } else {
        tickCount = axisSettings.getTickCount();
        tickInterval = axisSettings.getTickInterval();
    }

    if (tickInterval == null && tickCount == null) {
        return;
    }

    if (axis instanceof NumberAxis) {
        NumberAxis numberAxis = (NumberAxis) axis;
        int axisRange = (int) numberAxis.getRange().getLength();
        if (axisRange > 0) {
            if (tickInterval != null) {
                if (numberAxis.getNumberFormatOverride() != null) {
                    numberAxis.setTickUnit(new NumberTickUnit(tickInterval.doubleValue(),
                            numberAxis.getNumberFormatOverride()));
                } else {
                    numberAxis.setTickUnit(new NumberTickUnit(tickInterval.doubleValue()));
                }
            } else if (tickCount != null) {
                if (numberAxis.getNumberFormatOverride() != null) {
                    numberAxis.setTickUnit(new NumberTickUnit(axisRange / tickCount.intValue(),
                            numberAxis.getNumberFormatOverride()));
                } else {
                    numberAxis.setTickUnit(new NumberTickUnit(axisRange / tickCount.intValue()));
                }
            }
        }
    }
    //      else if(axis instanceof DateAxis)
    //      {
    //         DateAxis dateAxis = (DateAxis)axis;
    //         int axisRange = (int)dateAxis.getRange().getLength();
    //         if(dateAxis.getDateFormatOverride() != null)
    //         {
    //            dateAxis.setTickUnit(new DateTickUnit(timePeriodUnit, axisRange/tickCount, dateAxis.getDateFormatOverride()));
    //         }
    //         else
    //         {
    //            dateAxis.setTickUnit(new DateTickUnit(timePeriodUnit, axisRange/tickCount));
    //         }
    //      }
}

From source file:net.sf.fspdfs.chartthemes.spring.GenericChartTheme.java

/**
 * For a given axis, adjust the tick unit size, in order to 
 * have a customizable number of ticks on that axis
 *///from  w ww .  j  ava 2  s  . co m
protected void calculateTickUnits(Axis axis, boolean isRangeAxis, String timePeriodUnit) {
    Integer tickCount = null;
    Number tickInterval = null;

    if (getChart().hasProperties()) {
        String tickCountProperty = null;
        String tickIntervalProperty = null;
        if (isRangeAxis) {
            tickCountProperty = getChart().getPropertiesMap()
                    .getProperty(DefaultChartTheme.PROPERTY_RANGE_AXIS_TICK_COUNT);
            tickIntervalProperty = getChart().getPropertiesMap()
                    .getProperty(DefaultChartTheme.PROPERTY_RANGE_AXIS_TICK_INTERVAL);
        } else {
            tickCountProperty = getChart().getPropertiesMap()
                    .getProperty(DefaultChartTheme.PROPERTY_DOMAIN_AXIS_TICK_COUNT);
            tickIntervalProperty = getChart().getPropertiesMap()
                    .getProperty(DefaultChartTheme.PROPERTY_DOMAIN_AXIS_TICK_INTERVAL);
        }
        if (tickCountProperty != null && tickCountProperty.trim().length() > 0) {
            tickCount = Integer.valueOf(tickCountProperty);
        }
        if (tickIntervalProperty != null && tickIntervalProperty.trim().length() > 0) {
            tickInterval = Double.valueOf(tickIntervalProperty);
        }
    } else {
        if (isRangeAxis) {
            tickCount = (Integer) getDefaultValue(defaultAxisPropertiesMap,
                    ChartThemesConstants.RANGE_AXIS_TICK_COUNT);
            tickInterval = (Number) getDefaultValue(defaultAxisPropertiesMap,
                    ChartThemesConstants.RANGE_AXIS_TICK_INTERVAL);
        } else {
            tickCount = (Integer) getDefaultValue(defaultAxisPropertiesMap,
                    ChartThemesConstants.DOMAIN_AXIS_TICK_COUNT);
            tickInterval = (Number) getDefaultValue(defaultAxisPropertiesMap,
                    ChartThemesConstants.DOMAIN_AXIS_TICK_INTERVAL);
        }
    }

    if (tickInterval == null && tickCount == null) {
        return;
    }
    //      if(axis instanceof NumberAxis)
    //      {
    //         NumberAxis numberAxis = (NumberAxis)axis;
    //         int axisRange = (int)numberAxis.getRange().getLength();
    //         if(numberAxis.getNumberFormatOverride() != null)
    //         {
    //            if(tickInterval != null && tickInterval.length() > 0)
    //               numberAxis.setTickUnit(new NumberTickUnit(Double.valueOf(tickInterval).doubleValue(), numberAxis.getNumberFormatOverride()));
    //            else
    //               numberAxis.setTickUnit(new NumberTickUnit( axisRange/tickCount, numberAxis.getNumberFormatOverride()));
    //         }
    //         else
    //         {
    //            if(tickInterval != null && tickInterval.length() > 0)
    //               numberAxis.setTickUnit(new NumberTickUnit(Double.valueOf(tickInterval).doubleValue()));
    //            else
    //               numberAxis.setTickUnit(new NumberTickUnit(axisRange/tickCount));
    //         }
    //      }
    if (axis instanceof NumberAxis) {
        NumberAxis numberAxis = (NumberAxis) axis;
        int axisRange = (int) numberAxis.getRange().getLength();
        if (axisRange > 0) {
            if (tickInterval != null) {
                if (numberAxis.getNumberFormatOverride() != null) {
                    numberAxis.setTickUnit(new NumberTickUnit(tickInterval.doubleValue(),
                            numberAxis.getNumberFormatOverride()));
                } else {
                    numberAxis.setTickUnit(new NumberTickUnit(tickInterval.doubleValue()));
                }
            } else if (tickCount != null) {
                int newTickUnitSize = axisRange / tickCount.intValue();
                if (newTickUnitSize > numberAxis.getTickUnit().getSize()) {
                    int tickUnitSize = newTickUnitSize;

                    //preferably multiple of 5 values should be used as tick units lengths:
                    int i = 1;
                    while (tickUnitSize > 9) {
                        tickUnitSize /= 10;
                        i *= 10;
                    }
                    tickUnitSize *= i;
                    newTickUnitSize = tickUnitSize + i / 2;

                    if (newTickUnitSize > 0 && axisRange / newTickUnitSize > tickCount.intValue()) {
                        newTickUnitSize += i / 2;
                    }
                    if (numberAxis.getNumberFormatOverride() != null) {
                        numberAxis.setTickUnit(
                                new NumberTickUnit(newTickUnitSize, numberAxis.getNumberFormatOverride()));
                    } else {
                        numberAxis.setTickUnit(new NumberTickUnit(newTickUnitSize));
                    }
                }
            }
        }
    }
    //      else if(axis instanceof DateAxis)
    //      {
    //         DateAxis dateAxis = (DateAxis)axis;
    //         int axisRange = (int)dateAxis.getRange().getLength();
    //         int timeUnit = getTimePeriodUnit(timePeriodUnit);
    //         
    //         if(dateAxis.getDateFormatOverride() != null)
    //         {
    //            if(tickInterval != null && tickInterval.length() > 0)
    //               dateAxis.setTickUnit(new DateTickUnit(timeUnit, Integer.valueOf(tickInterval).intValue(), dateAxis.getDateFormatOverride()));
    //            else
    //               dateAxis.setTickUnit(new DateTickUnit(timeUnit, axisRange/tickCount, dateAxis.getDateFormatOverride()));
    //         }
    //         else
    //         {
    //            if(tickInterval != null && tickInterval.length() > 0)
    //               dateAxis.setTickUnit(new DateTickUnit(timeUnit, Integer.valueOf(tickInterval).intValue()));
    //            else
    //               dateAxis.setTickUnit(new DateTickUnit(timeUnit, axisRange/tickCount));
    //         }
    //      }
}