Example usage for org.jfree.chart.plot XYPlot setRangeAxis

List of usage examples for org.jfree.chart.plot XYPlot setRangeAxis

Introduction

In this page you can find the example usage for org.jfree.chart.plot XYPlot setRangeAxis.

Prototype

public void setRangeAxis(int index, ValueAxis axis) 

Source Link

Document

Sets a range axis and sends a PlotChangeEvent to all registered listeners.

Usage

From source file:GeMSE.Visualization.ElbowPlot.java

public void Plot(ArrayList<Double[]> pvData, ArrayList<Double[]> dData, int cut) {
    double maxY = 0;

    float[] secYColor = new float[3];
    Color.RGBtoHSB(153, 245, 255, secYColor);

    float[] priYColor = new float[3];
    Color.RGBtoHSB(255, 255, 255, priYColor);

    float[] cutColor = new float[3];
    Color.RGBtoHSB(255, 255, 0, cutColor);

    //create the series - add some dummy data
    XYSeries pvSeries = new XYSeries("Percentage of variance        ");
    for (int i = 1; i < pvData.size(); i++) {
        pvSeries.add(pvData.get(i)[0], pvData.get(i)[1]);
        maxY = Math.max(maxY, pvData.get(i)[1]);
    }//from   w w w. j  a va  2 s  . c  om

    XYSeries dSeries = new XYSeries("Percentage of differences between slopes        ");
    for (int i = 0; i < dData.size(); i++)
        dSeries.add(dData.get(i)[0], dData.get(i)[1]);

    XYSeries cutSeries = new XYSeries("Cut        ");
    cutSeries.add(cut, 0.0);
    cutSeries.add(cut, maxY);

    //create the datasets
    XYSeriesCollection pvDataSeries = new XYSeriesCollection();
    pvDataSeries.addSeries(pvSeries);

    XYSeriesCollection cutDataSeries = new XYSeriesCollection();
    cutDataSeries.addSeries(cutSeries);

    XYSeriesCollection dDataSeries = new XYSeriesCollection();
    dDataSeries.addSeries(dSeries);

    //construct the plot
    XYPlot plot = new XYPlot();
    plot.setDataset(0, pvDataSeries);
    plot.setDataset(1, cutDataSeries);
    plot.setDataset(2, dDataSeries);

    // use XYSplineRenderer if you want to smooth the lines.
    XYLineAndShapeRenderer pvRenderer = new XYLineAndShapeRenderer();
    pvRenderer.setSeriesPaint(0, Color.getHSBColor(priYColor[0], priYColor[1], priYColor[2]));

    BasicStroke dstroke = new BasicStroke(2.0f, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_ROUND, 1.0f,
            new float[] { 1.0f, 10.0f }, 0.0f);
    XYLineAndShapeRenderer dRenderer = new XYLineAndShapeRenderer();
    dRenderer.setSeriesPaint(0, Color.getHSBColor(secYColor[0], secYColor[1], secYColor[2]));
    dRenderer.setSeriesStroke(0, dstroke);

    BasicStroke cutStoke = new BasicStroke(4);
    // use XYSplineRenderer if you want to smooth the lines.
    //XYSplineRenderer cutRenderer = new XYSplineRenderer();
    XYLineAndShapeRenderer cutRenderer = new XYLineAndShapeRenderer();
    cutRenderer.setSeriesPaint(0, Color.getHSBColor(cutColor[0], cutColor[1], cutColor[2]));
    cutRenderer.setSeriesStroke(0, cutStoke);

    plot.setRenderer(0, pvRenderer);
    plot.setRenderer(1, cutRenderer);
    plot.setRenderer(2, dRenderer);

    plot.setRangeAxis(0, new NumberAxis("\n\nPercentage of Variance"));
    plot.setRangeAxis(1, new NumberAxis("Percentage of Difference Between Slopes"));
    plot.setDomainAxis(new NumberAxis("Number of Clusters\n\n"));

    //Map the data to the appropriate axis
    plot.mapDatasetToRangeAxis(0, 0);
    plot.mapDatasetToRangeAxis(1, 0);
    plot.mapDatasetToRangeAxis(2, 1);

    float[] hsbValues = new float[3];
    Color.RGBtoHSB(16, 23, 67, hsbValues);
    plot.setBackgroundPaint(Color.getHSBColor(hsbValues[0], hsbValues[1], hsbValues[2]));

    Font axisLabelFont = new Font("Dialog", Font.PLAIN, 14);
    Font axisTickLabelFont = new Font("Dialog", Font.PLAIN, 12);
    Font legendFont = new Font("Dialog", Font.PLAIN, 14);

    plot.setDomainGridlinePaint(Color.gray);
    plot.setRangeGridlinePaint(Color.gray);

    plot.getDomainAxis().setTickLabelPaint(Color.white);
    plot.getDomainAxis().setLabelPaint(Color.white);
    plot.getDomainAxis().setLabelFont(axisLabelFont);
    plot.getDomainAxis().setTickLabelFont(axisTickLabelFont);

    plot.getRangeAxis().setTickLabelPaint(Color.getHSBColor(priYColor[0], priYColor[1], priYColor[2]));
    plot.getRangeAxis().setLabelPaint(Color.getHSBColor(priYColor[0], priYColor[1], priYColor[2]));
    plot.getRangeAxis().setLabelFont(axisLabelFont);
    plot.getRangeAxis().setTickLabelFont(axisTickLabelFont);

    plot.getRangeAxis(1).setTickLabelPaint(Color.getHSBColor(secYColor[0], secYColor[1], secYColor[2]));
    plot.getRangeAxis(1).setLabelPaint(Color.getHSBColor(secYColor[0], secYColor[1], secYColor[2]));
    plot.getRangeAxis(1).setLabelFont(axisLabelFont);
    plot.getRangeAxis(1).setTickLabelFont(axisTickLabelFont);

    //generate the chart
    JFreeChart chart = new JFreeChart("\nSuggested number of clusters determined using Elbow method", getFont(),
            plot, true);

    chart.getTitle().setPaint(Color.white);
    chart.getLegend().setBackgroundPaint(Color.black);
    chart.getLegend().setItemPaint(Color.white);
    chart.getLegend().setPosition(RectangleEdge.BOTTOM);
    chart.getLegend().setItemFont(legendFont);

    float[] hsbValues2 = new float[3];
    Color.RGBtoHSB(36, 43, 87, hsbValues2);
    chart.setBackgroundPaint(Color.getHSBColor(hsbValues2[0], hsbValues2[1], hsbValues2[2]));
    JPanel chartPanel = new ChartPanel(chart);

    GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
    chartPanel.setPreferredSize(
            new java.awt.Dimension((int) Math.round((gd.getDisplayMode().getWidth() * 1.5) / 3.0),
                    (int) Math.round((gd.getDisplayMode().getHeight() * 1.5) / 3.0)));

    setContentPane(chartPanel);
}

From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.tabs.charts.GOESChartUIComponent.java

/***********************************************************************************************
 * Customise the XYPlot of a new chart, e.g. for fixed range axes.
 *
 * @param datasettype//  w ww  .j a  v a  2 s .  co m
 * @param primarydataset
 * @param secondarydatasets
 * @param updatetype
 * @param displaylimit
 * @param channelselector
 * @param debug
 *
 * @return JFreeChart
 */

public JFreeChart createCustomisedChart(final DatasetType datasettype, final XYDataset primarydataset,
        final List<XYDataset> secondarydatasets, final DataUpdateType updatetype, final int displaylimit,
        final ChannelSelectorUIComponentInterface channelselector, final boolean debug) {
    final JFreeChart jFreeChart;

    // A plain Chart is an XYPlot
    // with a DateAxis for the x-axis (index 0) and a NumberAxis for the y-axis (index 0).
    // The default renderer is an XYLineAndShapeRenderer
    jFreeChart = ChartHelper.createChart(primarydataset,
            ObservatoryInstrumentHelper.getCurrentObservatoryTimeZone(REGISTRY.getFramework(), getDAO(), debug),
            getMetadata(), getChannelCount(), hasTemperatureChannel(), updatetype, displaylimit,
            channelselector, debug);

    // Customise the Chart for GOES data
    // Channels 0 & 1 are Data on a LogarithmicAxis,
    // Channel 2 is Ratio on a NumberAxis
    if (jFreeChart != null) {
        final String strLabelFlux;
        final String strLabelRatio;
        final XYPlot plot;
        final LogarithmicAxis axisFlux;
        final DateAxis axisDate;

        // The set of Metadata available should include the Instrument
        // and any items from the current observation
        strLabelFlux = MetadataHelper.getMetadataValueByKey(getMetadata(),
                MetadataDictionary.KEY_OBSERVATION_AXIS_LABEL_Y.getKey()
                        + MetadataDictionary.SUFFIX_SERIES_ZERO);
        strLabelRatio = MetadataHelper.getMetadataValueByKey(getMetadata(),
                MetadataDictionary.KEY_OBSERVATION_AXIS_LABEL_Y.getKey()
                        + MetadataDictionary.SUFFIX_SERIES_ONE);

        plot = jFreeChart.getXYPlot();

        //----------------------------------------------------------------------------------
        // Replace the RangeAxis at index 0 NumberAxis with a LogarithmicAxis
        // The RangeAxis at index 0 is the LogarithmicAxis, to be used by Channels 0 & 1 (Data)

        axisFlux = new LogarithmicAxis(strLabelFlux);
        axisFlux.setRange(1.0E-09, 1.0E-02);
        axisFlux.setAllowNegativesFlag(false);
        axisFlux.setLog10TickLabelsFlag(true);
        plot.setRangeAxis(0, axisFlux);

        // Map the dataset to the axis
        plot.setDataset(INDEX_FLUX, primarydataset);
        plot.mapDatasetToRangeAxis(0, 0);
        plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_LEFT);

        //----------------------------------------------------------------------------------
        // Customise the DomainAxis at index 0

        axisDate = (DateAxis) plot.getDomainAxis();

        // Showing the YYYY-MM-DD makes a very long label...
        // ToDo Consider ThreadLocal
        axisDate.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss"));

        // Now customise the Flux renderer to improve legend visibility
        // Use the same colours as on http://www.swpc.noaa.gov/
        // blue=0.5 - 4.0A red=1.0 - 8.0A
        ChartUIHelper.customisePlotRenderer(plot, INDEX_FLUX);

        //----------------------------------------------------------------------------------
        // Set the RangeAxis at index 1 to a new NumberAxis, to be used by Channel 2 (Ratio)

        if ((secondarydatasets != null) && (secondarydatasets.size() == 1)) {
            final NumberAxis axisRatio;
            final XYLineAndShapeRenderer rendererRatio;

            axisRatio = new NumberAxis(strLabelRatio);
            plot.setRangeAxis(1, axisRatio);

            // The RangeAxis at index 1 is the NumberAxis, to be used by Channel 2
            plot.setDataset(INDEX_RATIO, secondarydatasets.get(0));
            plot.mapDatasetToRangeAxis(1, 1);
            plot.setRangeAxisLocation(1, AxisLocation.TOP_OR_RIGHT);

            rendererRatio = new XYLineAndShapeRenderer();
            rendererRatio.setLinesVisible(true);
            rendererRatio.setShapesVisible(false);
            // Channel 2 is Ratio
            rendererRatio.setSeriesPaint(0, ChartUIHelper.getStandardColour(2).getColor());
            rendererRatio.setLegendLine(SHAPE_LEGEND);

            plot.setRenderer(INDEX_RATIO, rendererRatio);
            //ChartHelper.customisePlotRenderer(plot, INDEX_RATIO);
        }
    }

    return (jFreeChart);
}

From source file:de.tor.tribes.ui.views.DSWorkbenchStatsFrame.java

private void addDataset(String pId, XYDataset pDataset) {
    if (chart == null) {
        setupChart(pId, pDataset);/* w ww .j  ava  2s.  c o m*/
    } else {
        XYPlot plot = (XYPlot) chart.getPlot();
        plot.setDataset(plot.getDatasetCount(), pDataset);
        NumberAxis axis = new NumberAxis(pId);
        NumberFormat nf = NumberFormat.getInstance();
        nf.setMinimumFractionDigits(0);
        nf.setMaximumFractionDigits(0);
        axis.setNumberFormatOverride(nf);
        plot.setRangeAxis(plot.getDatasetCount() - 1, axis);
        plot.setRangeAxisLocation(plot.getDatasetCount() - 1, AxisLocation.TOP_OR_LEFT);
        plot.mapDatasetToRangeAxis(plot.getDatasetCount() - 1, plot.getDatasetCount() - 1);
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        renderer.setSeriesLinesVisible(0, jShowLines.isSelected());
        renderer.setSeriesShapesVisible(0, jShowDataPoints.isSelected());
        plot.setRenderer(plot.getDatasetCount() - 1, renderer);
        renderer.setDefaultItemLabelsVisible(jShowItemValues.isSelected());
        renderer.setDefaultItemLabelGenerator(new org.jfree.chart.labels.StandardXYItemLabelGenerator());
        renderer.setDefaultToolTipGenerator(
                new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                        new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"), NumberFormat.getInstance()));
        axis.setAxisLinePaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint());
        axis.setLabelPaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint());
        axis.setTickLabelPaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint());
        axis.setTickMarkPaint(plot.getLegendItems().get(plot.getDatasetCount() - 1).getLinePaint());
    }
}

From source file:org.lmn.fc.frameworks.starbase.plugins.observatory.ui.tabs.charts.LogLinChartUIComponent.java

/***********************************************************************************************
 * Customise the XYPlot of a new chart, e.g. for fixed range axes.
 *
 * @param datasettype//w  w  w. j a v  a  2 s . co m
 * @param primarydataset
 * @param secondarydatasets
 * @param updatetype
 * @param displaylimit
 * @param channelselector
 * @param debug
 *
 * @return JFreeChart
 */

public JFreeChart createCustomisedChart(final DatasetType datasettype, final XYDataset primarydataset,
        final List<XYDataset> secondarydatasets, final DataUpdateType updatetype, final int displaylimit,
        final ChannelSelectorUIComponentInterface channelselector, final boolean debug) {
    final String SOURCE = "LogLinChartUIComponent.createCustomisedChart ";
    final JFreeChart jFreeChart;

    LOGGER.debug(debug, SOURCE + "--> ChartHelper.createChart()");

    MetadataHelper.showMetadataList(getMetadata(), SOURCE + " CHART METADATA --> ChartHelper.createChart()",
            LOADER_PROPERTIES.isMetadataDebug());

    channelselector.debugSelector(debug, SOURCE);

    // Creates TimeSeriesChart or XYLineChart to suit the dataset
    // The default renderer is an XYLineAndShapeRenderer
    jFreeChart = ChartHelper.createChart(primarydataset,
            ObservatoryInstrumentHelper.getCurrentObservatoryTimeZone(REGISTRY.getFramework(), getDAO(), debug),
            getMetadata(), getChannelCount(), hasTemperatureChannel(), updatetype, displaylimit,
            channelselector, debug);
    if (jFreeChart != null) {
        // Customise the Chart for LogLin data if possible
        if ((hasLogarithmicMode()) && (!channelselector.isLinearMode())) {
            final XYPlot plot;
            final LogarithmicAxis axisLog;
            final String strAxisLabel;

            LOGGER.debug(debug, SOURCE + "Customise the Chart for LogLin data");

            // The set of Metadata available should include the Instrument
            // and any items from the current observation
            strAxisLabel = MetadataHelper.getMetadataValueByKey(getMetadata(),
                    MetadataDictionary.KEY_OBSERVATION_AXIS_LABEL_Y.getKey()
                            + MetadataDictionary.SUFFIX_SERIES_ZERO);

            // Replace the RangeAxis at index 0 NumberAxis with a LogarithmicAxis
            axisLog = new LogarithmicAxis(strAxisLabel);

            axisLog.setAllowNegativesFlag(true);
            axisLog.setLog10TickLabelsFlag(true);

            if ((canAutorange()) && (channelselector.isAutoranging())) {
                axisLog.setAutoRange(true);
                axisLog.configure();
                axisLog.autoAdjustRange();
            } else {
                axisLog.setRange(getLogarithmicFixedMinY(), getLogarithmicFixedMaxY());
                axisLog.configure();
                axisLog.autoAdjustRange();
            }

            plot = jFreeChart.getXYPlot();
            plot.setRangeAxis(INDEX_AXIS, axisLog);
            plot.setRangeAxisLocation(INDEX_AXIS, AxisLocation.BOTTOM_OR_LEFT);

            // Map the dataset to the axis
            plot.setDataset(INDEX_DATA, primarydataset);
            plot.mapDatasetToRangeAxis(INDEX_DATA, INDEX_AXIS);

            // Change the DateAxis format
            if (DatasetType.TIMESTAMPED.equals(datasettype)) {
                final DateAxis axisDate;

                // Customise the DomainAxis at index 0
                axisDate = (DateAxis) plot.getDomainAxis();

                // Showing the YYYY-MM-DD makes a very long label...
                axisDate.setDateFormatOverride(new SimpleDateFormat("HH:mm:ss"));
            }

            // Now customise the data renderer to improve legend visibility
            ChartUIHelper.customisePlotRenderer(plot, 0);
        } else {
            final XYPlot plot;

            LOGGER.debug(debug, SOURCE + "Customise the Chart for Linear data");

            // Linear Mode

            // A default range suitable for display of dB
            ChartHelper.handleAutorangeForLinearMode(jFreeChart, channelselector, canAutorange(),
                    getLinearFixedMinY(), getLinearFixedMaxY(), debug);

            // Now customise the data renderer to improve legend visibility
            plot = jFreeChart.getXYPlot();
            ChartUIHelper.customisePlotRenderer(plot, 0);
        }
    } else {
        LOGGER.debug(debug, SOURCE + "Chart is NULL");
    }

    return (jFreeChart);
}

From source file:windows.sensorWindow.java

/**
 * creates all relevant data and adds it into the corresponding maps
 * /*from  w  w  w .  ja v a2 s .  c  om*/
 * @param UID
 *            UID of the plotting sensor
 */
@SuppressWarnings("deprecation")
public static void addPlot(Brick newBrick) {
    // create series
    TimeSeries newSeries = new TimeSeries("" + 0, Millisecond.class);
    TimeSeries newSeries2 = new TimeSeries("" + 0, Millisecond.class);
    TimeSeries newSeries3 = new TimeSeries("" + 0, Millisecond.class);
    TimeSeries newSeries4 = new TimeSeries("" + 0, Millisecond.class);
    TimeSeries newSeries5 = new TimeSeries("" + 0, Millisecond.class);
    TimeSeries newSeries6 = new TimeSeries("" + 0, Millisecond.class);

    Measurement m1 = new Measurement(maxValues, maxCycles, newBrick.uid, 0);
    valuesMap.put(newBrick.uid, m1);
    if (newBrick.checked3 == true) {
        Measurement m2 = new Measurement(maxValues, maxCycles, newBrick.uid, 1);
        values2Map.put(newBrick.uid, m2);
    }

    // create entry in state map
    plot1StateMap.put(newBrick.uid, 0);
    plot2StateMap.put(newBrick.uid, 0);

    // create index map entry
    tmplindex.put(newBrick.uid, 0);

    // create avrgCtrlEnabled maps
    if (newBrick.controlAverage == true)
        avrgCtrl1Enabled.put(newBrick.uid, true);
    else
        avrgCtrl1Enabled.put(newBrick.uid, false);
    if (newBrick.controlAverage2 == true)
        avrgCtrl2Enabled.put(newBrick.uid, true);
    else
        avrgCtrl2Enabled.put(newBrick.uid, false);

    // create series map entry
    seriesMap.put(newBrick.uid, newSeries);
    seriesMap2.put(newBrick.uid, newSeries2);
    seriesMap3.put(newBrick.uid, newSeries3);
    seriesMap4.put(newBrick.uid, newSeries4);
    seriesMap5.put(newBrick.uid, newSeries3);
    seriesMap6.put(newBrick.uid, newSeries4);

    // create collection map entry
    seriesCollectionMap.put(newBrick.uid, new TimeSeriesCollection(newSeries));
    seriesCollectionMap2.put(newBrick.uid, new TimeSeriesCollection(newSeries2));
    tmplCollection1_1.put(newBrick.uid, new TimeSeriesCollection(newSeries3));
    tmplCollection1_2.put(newBrick.uid, new TimeSeriesCollection(newSeries4));
    tmplCollection2_1.put(newBrick.uid, new TimeSeriesCollection(newSeries5));
    tmplCollection2_2.put(newBrick.uid, new TimeSeriesCollection(newSeries6));

    // create plot map entry, special case for current/voltage brick, since
    // it has 2 parallel measurements and therefore 2 graphs must be treated
    XYPlot tmpSubPlot;
    tmpSubPlot = new XYPlot(seriesCollectionMap.get(newBrick.uid), null, null, new StandardXYItemRenderer());

    // create the 1st graph
    if (newBrick.checked2 == true) {
        // create plot map entry
        NumberAxis rangeAxis = new NumberAxis(
                String.valueOf(constants.brickUnitMap.get(newBrick.deviceIdentifier)));
        rangeAxis.setAutoRangeIncludesZero(true);
        tmpSubPlot.setRangeAxis(0, rangeAxis);
        rangeAxis.setLabelPaint(Color.BLUE);
        rangeAxis.setVisible(newBrick.checked2);
        tmpSubPlot.setDataset(0, seriesCollectionMap.get(newBrick.uid));

        // set dot - shape
        // Shape cross = ShapeUtilities.createDiagonalCross(3, 1);

        // create and store renderer
        XYItemRenderer renderer1 = new XYLineAndShapeRenderer();
        renderer1 = tmpSubPlot.getRenderer();
        renderer1.setSeriesPaint(0, Color.BLUE);
        renderer1.setSeriesStroke(0, new BasicStroke(3));
        // line = dashes:
        // float dash[] = {5.0f};
        // renderer1.setSeriesStroke( 0, new
        // BasicStroke(3,BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER,
        // 10.0f, dash, 0.0f));
        // renderer1.setSeriesShape(0, cross);
        tmpSubPlot.setRenderer(0, renderer1);

        // set colors
        tmpSubPlot.setBackgroundPaint(Color.white);
        tmpSubPlot.setDomainGridlinePaint(Color.lightGray);
        tmpSubPlot.setRangeGridlinePaint(Color.lightGray);
        // tmpSubPlot.setRenderer(renderer2);

        // set font
        rangeAxis.setLabelFont(customFonts.get("axisLabelFont"));
        rangeAxis.setTickLabelFont(customFonts.get("axisValueFont"));

        // create template graph
        // if (newBrick.ctrlTmpl[0] == true)
        // {
        tmpSubPlot.setDataset(2, tmplCollection1_1.get(newBrick.uid));

        XYItemRenderer renderer3 = new XYLineAndShapeRenderer();
        int width = computeTmplPlotWidth(newBrick.tmpl1Width);
        BasicStroke stroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND);// , 10.0f, dash, 0.0f);
        renderer3.setSeriesPaint(0, Color.GREEN);
        // renderer3.setSeriesStroke( 0, new BasicStroke( 1 ) );
        renderer3.setSeriesStroke(0, stroke);
        renderer3.setSeriesVisible(0, newBrick.ctrlTmpl[0]);
        rendererMap3.put(newBrick.uid, renderer3);
        tmpSubPlot.setRenderer(2, rendererMap3.get(newBrick.uid));
        // }

        // put everything to the maps
        rendererMap.put(newBrick.uid, renderer1);
        plotMap.put(newBrick.uid, tmpSubPlot);
        axisMap.put(newBrick.uid, rangeAxis);
    }

    // create the 2nd graph
    if (newBrick.checked3 == true) {
        // set second axis for voltage/ampere brick
        NumberAxis secondaryAxis = new NumberAxis(
                String.valueOf(constants.brick2ndUnitMap.get(newBrick.deviceIdentifier)));
        secondaryAxis.setAutoRangeIncludesZero(true);
        tmpSubPlot.setRangeAxis(1, secondaryAxis);
        secondaryAxis.setLabelPaint(Color.RED);
        secondaryAxis.setVisible(newBrick.checked3);
        tmpSubPlot.setDataset(1, seriesCollectionMap2.get(newBrick.uid));
        tmpSubPlot.mapDatasetToRangeAxis(1, 1);

        // set font
        secondaryAxis.setLabelFont(customFonts.get("axisLabelFont"));
        secondaryAxis.setTickLabelFont(customFonts.get("axisValueFont"));

        // create and store renderer
        XYItemRenderer renderer2 = new StandardXYItemRenderer();
        // renderer2 = tmpSubPlot.getRenderer();
        renderer2.setSeriesPaint(1, Color.RED);
        renderer2.setSeriesStroke(0, new BasicStroke(3));
        tmpSubPlot.setRenderer(1, renderer2);

        // set colors
        tmpSubPlot.setBackgroundPaint(Color.white);
        tmpSubPlot.setDomainGridlinePaint(Color.lightGray);
        tmpSubPlot.setRangeGridlinePaint(Color.lightGray);

        // ----------------------------------------------------------------------------------
        // create min1 critical map value
        ValueMarker vm5 = new ValueMarker(newBrick.tresholdMin2);
        markerMapMin2Critical.put(newBrick.uid, vm5);
        // set critical line
        markerMapMin2Critical.get(newBrick.uid).setPaint(Color.red);
        markerMapMin2Critical.get(newBrick.uid).setLabel(
                String.valueOf(constants.brick2ndUnitMap.get(newBrick.deviceIdentifier)) + " critical min");
        markerMapMin2Critical.get(newBrick.uid).setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        markerMapMin2Critical.get(newBrick.uid).setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        tmpSubPlot.addRangeMarker(1, markerMapMin2Critical.get(newBrick.uid), Layer.BACKGROUND);

        // create min1 warning map value
        ValueMarker vm6 = new ValueMarker(
                newBrick.tresholdMin2 + newBrick.tresholdMin2 * warningPercentage / 100);
        markerMapMin2Warning.put(newBrick.uid, vm6);
        // set warning line
        markerMapMin2Warning.get(newBrick.uid).setPaint(Color.orange);
        markerMapMin2Warning.get(newBrick.uid).setLabel(
                String.valueOf(constants.brick2ndUnitMap.get(newBrick.deviceIdentifier)) + " warning min");
        markerMapMin2Warning.get(newBrick.uid).setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        markerMapMin2Warning.get(newBrick.uid).setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        // tmpSubPlot.addRangeMarker(markerMapMin2Warning.get(newBrick.uid));
        tmpSubPlot.addRangeMarker(1, markerMapMin2Warning.get(newBrick.uid), Layer.BACKGROUND);

        // create max1 critical map value
        ValueMarker vm7 = new ValueMarker(newBrick.tresholdMax2);
        markerMapMax2Critical.put(newBrick.uid, vm7);
        // set critical line
        markerMapMax2Critical.get(newBrick.uid).setPaint(Color.red);
        markerMapMax2Critical.get(newBrick.uid).setLabel(
                String.valueOf(constants.brick2ndUnitMap.get(newBrick.deviceIdentifier)) + " critical max");
        markerMapMax2Critical.get(newBrick.uid).setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        markerMapMax2Critical.get(newBrick.uid).setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        tmpSubPlot.addRangeMarker(1, markerMapMax2Critical.get(newBrick.uid), Layer.BACKGROUND);

        // create max1 warning map value
        ValueMarker vm8 = new ValueMarker(
                newBrick.tresholdMax2 + newBrick.tresholdMax2 * warningPercentage / 100);
        markerMapMax2Warning.put(newBrick.uid, vm8);
        // set warning line
        markerMapMax2Warning.get(newBrick.uid).setPaint(Color.orange);
        markerMapMax2Warning.get(newBrick.uid).setLabel(
                String.valueOf(constants.brick2ndUnitMap.get(newBrick.deviceIdentifier)) + " warning max");
        markerMapMax2Warning.get(newBrick.uid).setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        markerMapMax2Warning.get(newBrick.uid).setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        tmpSubPlot.addRangeMarker(1, markerMapMax2Warning.get(newBrick.uid), Layer.BACKGROUND);

        // create and add min, max and average markers
        // create maxima marker
        ValueMarker vmMax = new ValueMarker(0);
        vmMax.setPaint(Color.orange);
        vmMax.setLabel("max");
        vmMax.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        vmMax.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        // create minima marker
        ValueMarker vmMin = new ValueMarker(0);
        vmMin.setPaint(Color.orange);
        vmMin.setLabel("min");
        vmMin.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        vmMin.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        // create average marker
        ValueMarker vmAvg = new ValueMarker(0);
        vmAvg.setPaint(Color.red);
        vmAvg.setLabel("average");
        vmAvg.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        vmAvg.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        // add to maps
        marker2Maxima.put(newBrick.uid, vmMax);
        marker2Minima.put(newBrick.uid, vmMin);
        marker2Average.put(newBrick.uid, vmAvg);
        // add to plot
        tmpSubPlot.addRangeMarker(1, vmMax, Layer.BACKGROUND);
        tmpSubPlot.addRangeMarker(1, vmMin, Layer.BACKGROUND);
        tmpSubPlot.addRangeMarker(1, vmAvg, Layer.BACKGROUND);

        // create and add avrgCntrMarkers
        // create upper marker
        ValueMarker avrgCtrl2high = new ValueMarker(newBrick.getAvg2high());
        avrgCtrl2high.setPaint(Color.orange);
        avrgCtrl2high.setLabel("avrg high");
        avrgCtrl2high.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        avrgCtrl2high.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        // create lower marker
        ValueMarker avrgCtrl2low = new ValueMarker(newBrick.getAvg2low());
        avrgCtrl2low.setPaint(Color.orange);
        avrgCtrl2low.setLabel("avrg low");
        avrgCtrl2low.setLabelAnchor(RectangleAnchor.TOP_RIGHT);
        avrgCtrl2low.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
        // add both markers
        avrg2High.put(newBrick.uid, avrgCtrl2high);
        avrg2Low.put(newBrick.uid, avrgCtrl2low);
        // add both to plot
        if (newBrick.controlAverage2) {
            tmpSubPlot.addRangeMarker(1, avrgCtrl2high, Layer.BACKGROUND);
            tmpSubPlot.addRangeMarker(1, avrgCtrl2low, Layer.BACKGROUND);
        }
        // ----------------------------------------------------------------------------------

        // put everything to the map
        rendererMap2.put(newBrick.uid, renderer2);
        plotMap.put(newBrick.uid, tmpSubPlot);
        axisMap2.put(newBrick.uid, secondaryAxis);
    }

    // 1st graph
    // markers--------------------------------------------------------------------------------------------------
    // create min1 critical map value
    ValueMarker vm1 = new ValueMarker(newBrick.tresholdMin1);
    markerMapMin1Critical.put(newBrick.uid, vm1);
    // set critical line
    markerMapMin1Critical.get(newBrick.uid).setPaint(Color.red);
    // / .setLabel("critical");
    // markerMapMin1Critical.get(newBrick.uid).setLabelAnchor(RectangleAnchor.BOTTOM);
    markerMapMin1Critical.get(newBrick.uid)
            .setLabel(String.valueOf(constants.brickUnitMap.get(newBrick.deviceIdentifier)) + " critical min");
    markerMapMin1Critical.get(newBrick.uid).setLabelAnchor(RectangleAnchor.TOP_LEFT);
    markerMapMin1Critical.get(newBrick.uid).setLabelTextAnchor(TextAnchor.TOP_LEFT);
    plotMap.get(newBrick.uid).addRangeMarker(markerMapMin1Critical.get(newBrick.uid));

    // create min1 warning map value
    ValueMarker vm2 = new ValueMarker(newBrick.tresholdMin1 + newBrick.tresholdMin1 * warningPercentage / 100);
    markerMapMin1Warning.put(newBrick.uid, vm2);
    // set warning line
    markerMapMin1Warning.get(newBrick.uid).setPaint(Color.orange);
    // marker2Map.get(newBrick.uid).setPaint(Color.);
    // / marker2Map.get(newBrick.uid).setLabel("warning");
    markerMapMin1Warning.get(newBrick.uid)
            .setLabel(String.valueOf(constants.brickUnitMap.get(newBrick.deviceIdentifier)) + " warning min");
    markerMapMin1Warning.get(newBrick.uid).setLabelAnchor(RectangleAnchor.TOP_LEFT);
    markerMapMin1Warning.get(newBrick.uid).setLabelTextAnchor(TextAnchor.TOP_LEFT);
    plotMap.get(newBrick.uid).addRangeMarker(markerMapMin1Warning.get(newBrick.uid));

    // create max1 critical map value
    ValueMarker vm3 = new ValueMarker(newBrick.tresholdMax1);
    markerMapMax1Critical.put(newBrick.uid, vm3);
    // set critical line
    markerMapMax1Critical.get(newBrick.uid).setPaint(Color.red);
    // / .setLabel("critical");
    // markerMapMax1Critical.get(newBrick.uid).setLabelAnchor(RectangleAnchor.BOTTOM);
    markerMapMax1Critical.get(newBrick.uid)
            .setLabel(String.valueOf(constants.brickUnitMap.get(newBrick.deviceIdentifier)) + " critical max");
    markerMapMax1Critical.get(newBrick.uid).setLabelAnchor(RectangleAnchor.TOP_LEFT);
    markerMapMax1Critical.get(newBrick.uid).setLabelTextAnchor(TextAnchor.TOP_LEFT);
    plotMap.get(newBrick.uid).addRangeMarker(markerMapMax1Critical.get(newBrick.uid));

    // create max1 warning map value
    ValueMarker vm4 = new ValueMarker(newBrick.tresholdMax1 + newBrick.tresholdMax1 * warningPercentage / 100);
    markerMapMax1Warning.put(newBrick.uid, vm4);
    // set warning line
    markerMapMax1Warning.get(newBrick.uid).setPaint(Color.orange);
    markerMapMax1Warning.get(newBrick.uid)
            .setLabel(String.valueOf(constants.brickUnitMap.get(newBrick.deviceIdentifier)) + " warning max");
    markerMapMax1Warning.get(newBrick.uid).setLabelAnchor(RectangleAnchor.TOP_LEFT);
    markerMapMax1Warning.get(newBrick.uid).setLabelTextAnchor(TextAnchor.TOP_LEFT);
    plotMap.get(newBrick.uid).addRangeMarker(markerMapMax1Warning.get(newBrick.uid));

    // create and add min, max and average markers
    // create maxima marker
    ValueMarker vmMax = new ValueMarker(0);
    vmMax.setPaint(Color.cyan);
    vmMax.setLabel("max");
    vmMax.setLabelAnchor(RectangleAnchor.TOP_LEFT);
    vmMax.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    // create minima marker
    ValueMarker vmMin = new ValueMarker(0);
    vmMin.setPaint(Color.cyan);
    vmMin.setLabel("min");
    vmMin.setLabelAnchor(RectangleAnchor.TOP_LEFT);
    vmMin.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    // create average marker
    ValueMarker vmAvg = new ValueMarker(0);
    vmAvg.setPaint(Color.blue);
    vmAvg.setLabel("average");
    vmAvg.setLabelAnchor(RectangleAnchor.TOP_LEFT);
    vmAvg.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    // add to maps
    markerMaxima.put(newBrick.uid, vmMax);
    markerMinima.put(newBrick.uid, vmMin);
    markerAverage.put(newBrick.uid, vmAvg);
    // add to plot
    plotMap.get(newBrick.uid).addRangeMarker(vmMax);
    plotMap.get(newBrick.uid).addRangeMarker(vmMin);
    plotMap.get(newBrick.uid).addRangeMarker(vmAvg);

    // create and add avrgCntrMarkers
    // create upper marker
    ValueMarker avrgCtrl1high = new ValueMarker(newBrick.getAvg1high());
    avrgCtrl1high.setPaint(Color.orange);
    avrgCtrl1high.setLabel("avrg high");
    avrgCtrl1high.setLabelAnchor(RectangleAnchor.TOP_LEFT);
    avrgCtrl1high.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    // create lower marker
    ValueMarker avrgCtrl1low = new ValueMarker(newBrick.getAvg1low());
    avrgCtrl1low.setPaint(Color.orange);
    avrgCtrl1low.setLabel("avrg low");
    avrgCtrl1low.setLabelAnchor(RectangleAnchor.TOP_LEFT);
    avrgCtrl1low.setLabelTextAnchor(TextAnchor.TOP_LEFT);
    // add both markers
    avrg1High.put(newBrick.uid, avrgCtrl1high);
    avrg1Low.put(newBrick.uid, avrgCtrl1low);
    // add both to plot
    if (newBrick.controlAverage) {
        plotMap.get(newBrick.uid).addRangeMarker(avrgCtrl1high);
        plotMap.get(newBrick.uid).addRangeMarker(avrgCtrl1low);
    }
    // -----------------------------------------------------------------------------------------------------

    // set title
    NumberAxis axisForTitleOnly = new NumberAxis(
            data.constants.brickIdMap.get(newBrick.deviceIdentifier) + " (" + newBrick.uid + ")");
    axisForTitleOnly.setLabelFont(customFonts.get("titleFont"));
    axisForTitleOnly.setTickLabelsVisible(false);
    axisForTitleOnly.setTickMarksVisible(false);
    axisForTitleOnly.setMinorTickMarksVisible(false);
    axisForTitleOnly.setAxisLineVisible(false);
    plotMap.get(newBrick.uid).setDomainAxis(1, axisForTitleOnly);

    // add subplot to the main plot
    plot.add(plotMap.get(newBrick.uid));
}

From source file:netplot.GenericPlotPanel.java

void genericConfig(JFreeChart chart, XYPlot plot, int plotIndex) {
    if (!enableLegend) {
        chart.removeLegend();/*from  w  ww . j ava2 s. c  om*/
    }

    XYItemRenderer xyItemRenderer = plot.getRenderer();
    //May also be XYBarRenderer
    if (xyItemRenderer instanceof XYLineAndShapeRenderer) {
        XYToolTipGenerator xyToolTipGenerator = xyItemRenderer.getBaseToolTipGenerator();
        //If currently an XYLineAndShapeRenderer replace it so that we inc the colour for every plotIndex
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(linesEnabled, shapesEnabled);
        //Ensure we don't loose the tool tips on the new renderer
        renderer.setBaseToolTipGenerator(xyToolTipGenerator);
        renderer.setBasePaint(getPlotColour(plotIndex));
        renderer.setSeriesStroke(0, new BasicStroke(lineWidth, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL),
                true);
        plot.setRenderer(plotIndex, renderer);
    }

    //If we have a new y axis then we need a new data set
    if (yAxisName != null && yAxisName.length() > 0) {
        if (logYAxis) {
            LogAxis yAxis = new LogAxis(yAxisName);
            yAxis.setAutoRange(false);
            yAxis.setNumberFormatOverride(new LogFormat(10, "10", true));
            yAxis.setRange(minScaleValue, maxScaleValue);
            yAxis.setLowerBound(minScaleValue);
            yAxis.setUpperBound(maxScaleValue);
            plot.setRangeAxis(yAxisIndex, yAxis);
            plot.setRangeAxisLocation(yAxisIndex, AxisLocation.BOTTOM_OR_LEFT);
        } else {
            NumberAxis axis = new NumberAxis(yAxisName);
            axis.setAutoRangeIncludesZero(zeroOnYScale);
            if (autoScaleEnabled) {
                axis.setAutoRange(true);
            } else {
                Range range = new Range(minScaleValue, maxScaleValue);
                axis.setRangeWithMargins(range, true, true);
            }
            if (yAxisTickCount > 0) {
                NumberTickUnit tick = new NumberTickUnit(yAxisTickCount);
                axis.setTickUnit(tick);
            }
            plot.setRangeAxis(yAxisIndex, axis);
            plot.setRangeAxisLocation(yAxisIndex, AxisLocation.BOTTOM_OR_LEFT);
        }
        yAxisIndex++;
    }
    plot.mapDatasetToRangeAxis(plotIndex, yAxisIndex - 1);
    ValueAxis a = plot.getDomainAxis();
    if (xAxisName.length() > 0) {
        a.setLabel(xAxisName);
    }
    //We can enable/disable zero on the axis if we have a NumberAxis
    if (a instanceof NumberAxis) {
        ((NumberAxis) a).setAutoRangeIncludesZero(zeroOnXScale);
    }
}

From source file:org.n52.server.sos.render.DiagramRenderer.java

/**
 * <pre>/*from w  ww. j a v a  2s .  co m*/
 * dataset :=  associated to one range-axis;
 * corresponds to one observedProperty;
 * may contain multiple series;
 * series :=   corresponds to a time series for one foi
 * </pre>
 * 
 * .
 * 
 * @param entireCollMap
 *            the entire coll map
 * @param options
 *            the options
 * @param begin
 *            the begin
 * @param end
 *            the end
 * @param compress
 * @return the j free chart
 */
public JFreeChart renderChart(Map<String, OXFFeatureCollection> entireCollMap, DesignOptions options,
        Calendar begin, Calendar end, boolean compress) {

    DesignDescriptionList designDescriptions = buildUpDesignDescriptionList(options);

    /*** FIRST RUN ***/
    JFreeChart chart = initializeTimeSeriesChart();
    chart.setBackgroundPaint(Color.white);

    if (!this.isOverview) {
        chart.addSubtitle(new TextTitle(ConfigurationContext.COPYRIGHT, new Font(LABEL_FONT, Font.PLAIN, 9),
                Color.black, RectangleEdge.BOTTOM, HorizontalAlignment.RIGHT, VerticalAlignment.BOTTOM,
                new RectangleInsets(0, 0, 20, 20)));
    }
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setAxisOffset(new RectangleInsets(2.0, 2.0, 2.0, 2.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    plot.setDomainGridlinesVisible(options.getGrid());
    plot.setRangeGridlinesVisible(options.getGrid());

    // add additional datasets:
    DateAxis dateAxis = (DateAxis) plot.getDomainAxis();
    dateAxis.setRange(begin.getTime(), end.getTime());
    dateAxis.setDateFormatOverride(new SimpleDateFormat());

    // add all axes
    String[] phenomenaIds = options.getAllPhenomenIds();
    // all the axis indices to map them later
    HashMap<String, Integer> axes = new HashMap<String, Integer>();
    for (int i = 0; i < phenomenaIds.length; i++) {
        axes.put(phenomenaIds[i], i);
        plot.setRangeAxis(i, new NumberAxis(phenomenaIds[i]));
    }

    // list range markers
    ArrayList<ValueMarker> referenceMarkers = new ArrayList<ValueMarker>();
    HashMap<String, double[]> referenceBounds = new HashMap<String, double[]>();

    // create all TS collections
    for (int i = 0; i < options.getProperties().size(); i++) {

        TimeseriesProperties prop = options.getProperties().get(i);

        String phenomenonId = prop.getPhenomenon();

        TimeSeriesCollection dataset = createDataset(entireCollMap, prop, phenomenonId, compress);
        dataset.setGroup(new DatasetGroup(prop.getTimeseriesId()));
        XYDataset additionalDataset = dataset;

        NumberAxis axe = (NumberAxis) plot.getRangeAxis(axes.get(phenomenonId));

        if (this.isOverview) {
            axe.setAutoRange(true);
            axe.setAutoRangeIncludesZero(false);
        } else if (prop.getAxisUpperBound() == prop.getAxisLowerBound() || prop.isAutoScale()) {
            if (prop.isZeroScaled()) {
                axe.setAutoRangeIncludesZero(true);
            } else {
                axe.setAutoRangeIncludesZero(false);
            }
        } else {
            if (prop.isZeroScaled()) {
                if (axe.getUpperBound() < prop.getAxisUpperBound()) {
                    axe.setUpperBound(prop.getAxisUpperBound());
                }
                if (axe.getLowerBound() > prop.getAxisLowerBound()) {
                    axe.setLowerBound(prop.getAxisLowerBound());
                }
            } else {
                axe.setRange(prop.getAxisLowerBound(), prop.getAxisUpperBound());
                axe.setAutoRangeIncludesZero(false);
            }
        }

        plot.setDataset(i, additionalDataset);
        plot.mapDatasetToRangeAxis(i, axes.get(phenomenonId));

        // set bounds new for reference values
        if (!referenceBounds.containsKey(phenomenonId)) {
            double[] bounds = new double[] { axe.getLowerBound(), axe.getUpperBound() };
            referenceBounds.put(phenomenonId, bounds);
        } else {
            double[] bounds = referenceBounds.get(phenomenonId);
            if (bounds[0] >= axe.getLowerBound()) {
                bounds[0] = axe.getLowerBound();
            }
            if (bounds[1] <= axe.getUpperBound()) {
                bounds[1] = axe.getUpperBound();
            }
        }

        double[] bounds = referenceBounds.get(phenomenonId);
        for (String string : prop.getReferenceValues()) {
            if (prop.getRefValue(string).show()) {
                Double value = prop.getRefValue(string).getValue();
                if (value <= bounds[0]) {
                    bounds[0] = value;
                } else if (value >= bounds[1]) {
                    bounds[1] = value;
                }
            }
        }

        Axis axis = prop.getAxis();
        if (axis == null) {
            axis = new Axis(axe.getUpperBound(), axe.getLowerBound());
        } else if (prop.isAutoScale()) {
            axis.setLowerBound(axe.getLowerBound());
            axis.setUpperBound(axe.getUpperBound());
            axis.setMaxY(axis.getMaxY());
            axis.setMinY(axis.getMinY());
        }
        prop.setAxisData(axis);
        this.axisMapping.put(prop.getTimeseriesId(), axis);

        for (String string : prop.getReferenceValues()) {
            if (prop.getRefValue(string).show()) {
                referenceMarkers.add(new ValueMarker(prop.getRefValue(string).getValue(),
                        Color.decode(prop.getRefValue(string).getColor()),
                        new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f)));
            }
        }

        plot.mapDatasetToRangeAxis(i, axes.get(phenomenonId));
    }

    for (ValueMarker valueMarker : referenceMarkers) {
        plot.addRangeMarker(valueMarker);
    }

    // show actual time
    ValueMarker nowMarker = new ValueMarker(System.currentTimeMillis(), Color.orange,
            new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f));
    plot.addDomainMarker(nowMarker);

    if (!this.isOverview) {
        Iterator<Entry<String, double[]>> iterator = referenceBounds.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, double[]> boundsEntry = iterator.next();
            String phenId = boundsEntry.getKey();
            NumberAxis axe = (NumberAxis) plot.getRangeAxis(axes.get(phenId));
            axe.setAutoRange(true);
            // add a margin 
            double marginOffset = (boundsEntry.getValue()[1] - boundsEntry.getValue()[0]) / 25;
            boundsEntry.getValue()[0] -= marginOffset;
            boundsEntry.getValue()[1] += marginOffset;
            axe.setRange(boundsEntry.getValue()[0], boundsEntry.getValue()[1]);
        }
    }

    /**** SECOND RUN ***/

    // set domain axis labels:
    plot.getDomainAxis().setLabelFont(label);
    plot.getDomainAxis().setLabelPaint(LABEL_COLOR);
    plot.getDomainAxis().setTickLabelFont(tickLabelDomain);
    plot.getDomainAxis().setTickLabelPaint(LABEL_COLOR);
    plot.getDomainAxis().setLabel(designDescriptions.getDomainAxisLabel());

    // define the design for each series:
    for (int datasetIndex = 0; datasetIndex < plot.getDatasetCount(); datasetIndex++) {
        TimeSeriesCollection dataset = (TimeSeriesCollection) plot.getDataset(datasetIndex);

        for (int seriesIndex = 0; seriesIndex < dataset.getSeriesCount(); seriesIndex++) {

            String timeseriesId = (String) dataset.getSeries(seriesIndex).getKey();
            RenderingDesign dd = designDescriptions.get(timeseriesId);

            if (dd != null) {

                // LINESTYLE:
                String lineStyle = dd.getLineStyle();
                int width = dd.getLineWidth();
                if (this.isOverview) {
                    width = width / 2;
                    width = (width == 0) ? 1 : width;
                }
                // "1" is lineStyle "line"
                if (lineStyle.equalsIgnoreCase(LINE)) {
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(true, false);
                    ren.setStroke(new BasicStroke(width));
                    plot.setRenderer(datasetIndex, ren);
                }
                // "2" is lineStyle "area"
                else if (lineStyle.equalsIgnoreCase(AREA)) {
                    plot.setRenderer(datasetIndex, new XYAreaRenderer());
                }
                // "3" is lineStyle "dotted"
                else if (lineStyle.equalsIgnoreCase(DOTTED)) {
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(false, true);
                    ren.setShape(new Ellipse2D.Double(-width, -width, 2 * width, 2 * width));
                    plot.setRenderer(datasetIndex, ren);

                }
                // "4" is dashed
                else if (lineStyle.equalsIgnoreCase("4")) {
                    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
                    renderer.setSeriesStroke(0, new BasicStroke(width, BasicStroke.CAP_ROUND,
                            BasicStroke.JOIN_ROUND, 1.0f, new float[] { 4.0f * width, 4.0f * width }, 0.0f));
                    plot.setRenderer(datasetIndex, renderer);
                } else if (lineStyle.equalsIgnoreCase("5")) {
                    // lines and dots
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(true, true);
                    int thickness = 2 * width;
                    ren.setShape(new Ellipse2D.Double(-width, -width, thickness, thickness));
                    ren.setStroke(new BasicStroke(width));
                    plot.setRenderer(datasetIndex, ren);
                } else {
                    // default is lineStyle "line"
                    plot.setRenderer(datasetIndex, new XYLineAndShapeRenderer(true, false));
                }

                plot.getRenderer(datasetIndex).setSeriesPaint(seriesIndex, dd.getColor());

                // plot.getRenderer(datasetIndex).setShapesVisible(true);

                XYToolTipGenerator toolTipGenerator = StandardXYToolTipGenerator.getTimeSeriesInstance();
                XYURLGenerator urlGenerator = new MetadataInURLGenerator(designDescriptions);

                plot.getRenderer(datasetIndex).setBaseToolTipGenerator(toolTipGenerator);
                plot.getRenderer(datasetIndex).setURLGenerator(urlGenerator);

                // GRID:
                // PROBLEM: JFreeChart only allows to switch the grid on/off
                // for the whole XYPlot. And the
                // grid will always be displayed for the first series in the
                // plot. I'll always show the
                // grid.
                // --> plot.setDomainGridlinesVisible(visible)

                // RANGE AXIS LABELS:
                if (isOverview) {
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelsVisible(false);
                    plot.getRangeAxisForDataset(datasetIndex).setTickMarksVisible(false);
                    plot.getRangeAxisForDataset(datasetIndex).setVisible(false);
                } else {
                    plot.getRangeAxisForDataset(datasetIndex).setLabelFont(label);
                    plot.getRangeAxisForDataset(datasetIndex).setLabelPaint(LABEL_COLOR);
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelFont(tickLabelDomain);
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelPaint(LABEL_COLOR);
                    StringBuilder unitOfMeasure = new StringBuilder();
                    unitOfMeasure.append(dd.getPhenomenon().getLabel());
                    String uomLabel = dd.getUomLabel();
                    if (uomLabel != null && !uomLabel.isEmpty()) {
                        unitOfMeasure.append(" (").append(uomLabel).append(")");
                    }
                    plot.getRangeAxisForDataset(datasetIndex).setLabel(unitOfMeasure.toString());
                }
            }
        }
    }
    return chart;
}

From source file:org.n52.server.io.render.DiagramRenderer.java

/**
 * <pre>/*from w  w  w. ja v a  2  s . com*/
 * dataset :=  associated to one range-axis;
 * corresponds to one observedProperty;
 * may contain multiple series;
 * series :=   corresponds to a time series for one foi
 * </pre>
 *
 * .
 *
 * @param entireCollMap
 *            the entire coll map
 * @param options
 *            the options
 * @param begin
 *            the begin
 * @param end
 *            the end
 * @param compress
 * @return the j free chart
 */
public JFreeChart renderChart(Map<String, OXFFeatureCollection> entireCollMap, DesignOptions options,
        Calendar begin, Calendar end, boolean compress) {

    DesignDescriptionList designDescriptions = buildUpDesignDescriptionList(options);

    /*** FIRST RUN ***/
    JFreeChart chart = initializeTimeSeriesChart();
    chart.setBackgroundPaint(Color.white);

    if (!this.isOverview) {
        chart.addSubtitle(new TextTitle(ConfigurationContext.COPYRIGHT, new Font(LABEL_FONT, Font.PLAIN, 9),
                Color.black, RectangleEdge.BOTTOM, HorizontalAlignment.RIGHT, VerticalAlignment.BOTTOM,
                new RectangleInsets(0, 0, 20, 20)));
    }
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.lightGray);
    plot.setAxisOffset(new RectangleInsets(2.0, 2.0, 2.0, 2.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    plot.setDomainGridlinesVisible(options.getGrid());
    plot.setRangeGridlinesVisible(options.getGrid());

    // add additional datasets:
    DateAxis dateAxis = (DateAxis) plot.getDomainAxis();
    dateAxis.setRange(begin.getTime(), end.getTime());
    dateAxis.setDateFormatOverride(new SimpleDateFormat());
    dateAxis.setTimeZone(end.getTimeZone());

    // add all axes
    String[] phenomenaIds = options.getAllPhenomenIds();
    // all the axis indices to map them later
    HashMap<String, Integer> axes = new HashMap<String, Integer>();
    for (int i = 0; i < phenomenaIds.length; i++) {
        axes.put(phenomenaIds[i], i);
        plot.setRangeAxis(i, new NumberAxis(phenomenaIds[i]));
    }

    // list range markers
    ArrayList<ValueMarker> referenceMarkers = new ArrayList<ValueMarker>();
    HashMap<String, double[]> referenceBounds = new HashMap<String, double[]>();

    // create all TS collections
    for (int i = 0; i < options.getProperties().size(); i++) {

        TimeseriesProperties prop = options.getProperties().get(i);

        String phenomenonId = prop.getPhenomenon();

        TimeSeriesCollection dataset = createDataset(entireCollMap, prop, phenomenonId, compress);
        dataset.setGroup(new DatasetGroup(prop.getTimeseriesId()));
        XYDataset additionalDataset = dataset;

        NumberAxis axe = (NumberAxis) plot.getRangeAxis(axes.get(phenomenonId));

        if (this.isOverview) {
            axe.setAutoRange(true);
            axe.setAutoRangeIncludesZero(false);
        } else if (prop.getAxisUpperBound() == prop.getAxisLowerBound() || prop.isAutoScale()) {
            if (prop.isZeroScaled()) {
                axe.setAutoRangeIncludesZero(true);
            } else {
                axe.setAutoRangeIncludesZero(false);
            }
        } else {
            if (prop.isZeroScaled()) {
                if (axe.getUpperBound() < prop.getAxisUpperBound()) {
                    axe.setUpperBound(prop.getAxisUpperBound());
                }
                if (axe.getLowerBound() > prop.getAxisLowerBound()) {
                    axe.setLowerBound(prop.getAxisLowerBound());
                }
            } else {
                axe.setRange(prop.getAxisLowerBound(), prop.getAxisUpperBound());
                axe.setAutoRangeIncludesZero(false);
            }
        }

        plot.setDataset(i, additionalDataset);
        plot.mapDatasetToRangeAxis(i, axes.get(phenomenonId));

        // set bounds new for reference values
        if (!referenceBounds.containsKey(phenomenonId)) {
            double[] bounds = new double[] { axe.getLowerBound(), axe.getUpperBound() };
            referenceBounds.put(phenomenonId, bounds);
        } else {
            double[] bounds = referenceBounds.get(phenomenonId);
            if (bounds[0] >= axe.getLowerBound()) {
                bounds[0] = axe.getLowerBound();
            }
            if (bounds[1] <= axe.getUpperBound()) {
                bounds[1] = axe.getUpperBound();
            }
        }

        double[] bounds = referenceBounds.get(phenomenonId);
        for (String string : prop.getReferenceValues()) {
            if (prop.getRefValue(string).show()) {
                Double value = prop.getRefValue(string).getValue();
                if (value <= bounds[0]) {
                    bounds[0] = value;
                } else if (value >= bounds[1]) {
                    bounds[1] = value;
                }
            }
        }

        Axis axis = prop.getAxis();
        if (axis == null) {
            axis = new Axis(axe.getUpperBound(), axe.getLowerBound());
        } else if (prop.isAutoScale()) {
            axis.setLowerBound(axe.getLowerBound());
            axis.setUpperBound(axe.getUpperBound());
            axis.setMaxY(axis.getMaxY());
            axis.setMinY(axis.getMinY());
        }
        prop.setAxisData(axis);
        this.axisMapping.put(prop.getTimeseriesId(), axis);

        for (String string : prop.getReferenceValues()) {
            if (prop.getRefValue(string).show()) {
                referenceMarkers.add(new ValueMarker(prop.getRefValue(string).getValue(),
                        Color.decode(prop.getRefValue(string).getColor()),
                        new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f)));
            }
        }

        plot.mapDatasetToRangeAxis(i, axes.get(phenomenonId));
    }

    for (ValueMarker valueMarker : referenceMarkers) {
        plot.addRangeMarker(valueMarker);
    }

    // show actual time
    ValueMarker nowMarker = new ValueMarker(System.currentTimeMillis(), Color.orange,
            new BasicStroke(1.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f));
    plot.addDomainMarker(nowMarker);

    if (!this.isOverview) {
        Iterator<Entry<String, double[]>> iterator = referenceBounds.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, double[]> boundsEntry = iterator.next();
            String phenId = boundsEntry.getKey();
            NumberAxis axe = (NumberAxis) plot.getRangeAxis(axes.get(phenId));
            axe.setAutoRange(true);
            // add a margin
            double marginOffset = (boundsEntry.getValue()[1] - boundsEntry.getValue()[0]) / 25;
            boundsEntry.getValue()[0] -= marginOffset;
            boundsEntry.getValue()[1] += marginOffset;
            axe.setRange(boundsEntry.getValue()[0], boundsEntry.getValue()[1]);
        }
    }

    /**** SECOND RUN ***/

    // set domain axis labels:
    plot.getDomainAxis().setLabelFont(label);
    plot.getDomainAxis().setLabelPaint(LABEL_COLOR);
    plot.getDomainAxis().setTickLabelFont(tickLabelDomain);
    plot.getDomainAxis().setTickLabelPaint(LABEL_COLOR);
    plot.getDomainAxis().setLabel(designDescriptions.getDomainAxisLabel());

    // define the design for each series:
    for (int datasetIndex = 0; datasetIndex < plot.getDatasetCount(); datasetIndex++) {
        TimeSeriesCollection dataset = (TimeSeriesCollection) plot.getDataset(datasetIndex);

        for (int seriesIndex = 0; seriesIndex < dataset.getSeriesCount(); seriesIndex++) {

            String timeseriesId = (String) dataset.getSeries(seriesIndex).getKey();
            RenderingDesign dd = designDescriptions.get(timeseriesId);

            if (dd != null) {

                // LINESTYLE:
                String lineStyle = dd.getLineStyle();
                int width = dd.getLineWidth();
                if (this.isOverview) {
                    width = width / 2;
                    width = (width == 0) ? 1 : width;
                }
                // "1" is lineStyle "line"
                if (lineStyle.equalsIgnoreCase(LINE)) {
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(true, false);
                    ren.setStroke(new BasicStroke(width));
                    plot.setRenderer(datasetIndex, ren);
                }
                // "2" is lineStyle "area"
                else if (lineStyle.equalsIgnoreCase(AREA)) {
                    plot.setRenderer(datasetIndex, new XYAreaRenderer());
                }
                // "3" is lineStyle "dotted"
                else if (lineStyle.equalsIgnoreCase(DOTTED)) {
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(false, true);
                    ren.setShape(new Ellipse2D.Double(-width, -width, 2 * width, 2 * width));
                    plot.setRenderer(datasetIndex, ren);

                }
                // "4" is dashed
                else if (lineStyle.equalsIgnoreCase("4")) { // dashed
                    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false);
                    renderer.setSeriesStroke(0, new BasicStroke(width, BasicStroke.CAP_ROUND,
                            BasicStroke.JOIN_ROUND, 1.0f, new float[] { 4.0f * width, 4.0f * width }, 0.0f));
                    plot.setRenderer(datasetIndex, renderer);
                } else if (lineStyle.equalsIgnoreCase("5")) {
                    // lines and dots
                    XYLineAndShapeRenderer ren = new XYLineAndShapeRenderer(true, true);
                    int thickness = 2 * width;
                    ren.setShape(new Ellipse2D.Double(-width, -width, thickness, thickness));
                    ren.setStroke(new BasicStroke(width));
                    plot.setRenderer(datasetIndex, ren);
                } else {
                    // default is lineStyle "line"
                    plot.setRenderer(datasetIndex, new XYLineAndShapeRenderer(true, false));
                }

                plot.getRenderer(datasetIndex).setSeriesPaint(seriesIndex, dd.getColor());

                // plot.getRenderer(datasetIndex).setShapesVisible(true);

                XYToolTipGenerator toolTipGenerator = StandardXYToolTipGenerator.getTimeSeriesInstance();
                XYURLGenerator urlGenerator = new MetadataInURLGenerator(designDescriptions);

                plot.getRenderer(datasetIndex).setBaseToolTipGenerator(toolTipGenerator);
                plot.getRenderer(datasetIndex).setURLGenerator(urlGenerator);

                // GRID:
                // PROBLEM: JFreeChart only allows to switch the grid on/off
                // for the whole XYPlot. And the
                // grid will always be displayed for the first series in the
                // plot. I'll always show the
                // grid.
                // --> plot.setDomainGridlinesVisible(visible)

                // RANGE AXIS LABELS:
                if (isOverview) {
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelsVisible(false);
                    plot.getRangeAxisForDataset(datasetIndex).setTickMarksVisible(false);
                    plot.getRangeAxisForDataset(datasetIndex).setVisible(false);
                } else {
                    plot.getRangeAxisForDataset(datasetIndex).setLabelFont(label);
                    plot.getRangeAxisForDataset(datasetIndex).setLabelPaint(LABEL_COLOR);
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelFont(tickLabelDomain);
                    plot.getRangeAxisForDataset(datasetIndex).setTickLabelPaint(LABEL_COLOR);
                    StringBuilder unitOfMeasure = new StringBuilder();
                    unitOfMeasure.append(dd.getPhenomenon().getLabel());
                    String uomLabel = dd.getUomLabel();
                    if (uomLabel != null && !uomLabel.isEmpty()) {
                        unitOfMeasure.append(" (").append(uomLabel).append(")");
                    }
                    plot.getRangeAxisForDataset(datasetIndex).setLabel(unitOfMeasure.toString());
                }
            }
        }
    }
    return chart;
}

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

/**
 * Build and configure a multiple axis chart.  A multiple axis chart support more than
 * one range axis.  Multiple datasets using different ranges can be displayed as long as
 * they share a common domain axis.  Each dataset can be rendered differently, so one chart
 * can contain (for example) two line charts, a bar chart and an area chart.
 * <br><br>// w  ww.  j a va2  s. c  o m
 * Multiple axis charts are handled differently than the other chart types.  They do not
 * have a dataset, as each chart that is added to the multiple axis chart has its own
 * dataset.  For simplicity, each dataset is treated as its own chart, and in fact we
 * reuse the design of all the chart types and let JFreeChart actually run them.  Then
 * we pull out the bits we need and add it to the common chart.  All the plot and chart
 * options on the nested charts is ignored, and all formatting is controlled by the plot
 * attached to the multiAxisChart.  The one exception is seriesColor, which can be used in
 * a nested report to specify a color for a specific series in that report.
 *
 * @param evaluation current expression evaluation phase
 * @throws JRException
 */
protected void createMultiAxisChart(byte evaluation) throws JRException {
    // A multi axis chart has to have at least one axis and chart specified.
    // Create the first axis as the base plot, and then go ahead and create the
    // charts for any additional axes.  Just take the renderer and data series
    // from those charts and add them to the first one.
    Plot mainPlot = null;

    JRFillMultiAxisPlot jrPlot = (JRFillMultiAxisPlot) getPlot();

    // create a multi axis hyperlink provider
    MultiAxisChartHyperlinkProvider multiHyperlinkProvider = new MultiAxisChartHyperlinkProvider();

    // Generate the main plot from the first axes specified.
    Iterator<JRChartAxis> iter = jrPlot.getAxes().iterator();
    if (iter.hasNext()) {
        JRFillChartAxis axis = (JRFillChartAxis) iter.next();
        JRFillChart fillChart = axis.getFillChart();

        //a JFreeChart object should be obtained first; the rendering type should be always "vector"

        jfreeChart = fillChart.evaluateChart(evaluation);
        //FIXME honor printWhenExpression
        // Override the plot from the first axis with the plot for the multi-axis
        // chart.
        //FIXME is the above comment true? 
        //configureChart(jfreeChart, getPlot(), evaluation);
        mainPlot = jfreeChart.getPlot();
        ChartHyperlinkProvider axisHyperlinkProvider = fillChart.getHyperlinkProvider();

        if (mainPlot instanceof CategoryPlot) {
            CategoryPlot categoryPlot = (CategoryPlot) mainPlot;
            categoryPlot.setRangeAxisLocation(0, getChartAxisLocation(axis));
            if (axisHyperlinkProvider != null) {
                multiHyperlinkProvider.addHyperlinkProvider(categoryPlot.getDataset(), axisHyperlinkProvider);
            }
        } else if (mainPlot instanceof XYPlot) {
            XYPlot xyPlot = (XYPlot) mainPlot;
            xyPlot.setRangeAxisLocation(0, getChartAxisLocation(axis));
            if (axisHyperlinkProvider != null) {
                multiHyperlinkProvider.addHyperlinkProvider(xyPlot.getDataset(), axisHyperlinkProvider);
            }
        }
    }

    // Now handle all the extra axes, if any.
    int axisNumber = 0;
    while (iter.hasNext()) {
        JRFillChartAxis chartAxis = (JRFillChartAxis) iter.next();
        JRFillChart fillChart = chartAxis.getFillChart();

        fillChart.evaluatePrintWhenExpression(evaluation);
        if (!(fillChart.isPrintWhenExpressionNull() || fillChart.isPrintWhenTrue())) {
            continue;
        }

        axisNumber++;
        JFreeChart axisChart = fillChart.evaluateChart(evaluation);
        ChartHyperlinkProvider axisHyperlinkProvider = fillChart.getHyperlinkProvider();

        // In JFreeChart to add a second chart type to an existing chart
        // you need to add an axis, a data series and a renderer.  To
        // leverage existing code we simply create a new chart for the
        // axis and then pull out the bits we need and add them to the multi
        // chart.  Currently JFree only supports category plots and xy plots
        // in a multi-axis chart, and you can not mix the two.
        if (mainPlot instanceof CategoryPlot) {
            CategoryPlot mainCatPlot = (CategoryPlot) mainPlot;
            if (!(axisChart.getPlot() instanceof CategoryPlot)) {
                throw new JRException(EXCEPTION_MESSAGE_KEY_MULTIAXIS_PLOT_TYPES_MIX_NOT_ALLOWED,
                        (Object[]) null);
            }

            // Get the axis and add it to the multi axis chart plot
            CategoryPlot axisPlot = (CategoryPlot) axisChart.getPlot();
            mainCatPlot.setRangeAxis(axisNumber, axisPlot.getRangeAxis());
            mainCatPlot.setRangeAxisLocation(axisNumber, getChartAxisLocation(chartAxis));

            // Add the data set and map it to the recently added axis
            mainCatPlot.setDataset(axisNumber, axisPlot.getDataset());
            mainCatPlot.mapDatasetToRangeAxis(axisNumber, axisNumber);

            // Set the renderer to use to draw the dataset.
            mainCatPlot.setRenderer(axisNumber, axisPlot.getRenderer());

            // Handle any color series for this chart
            configureAxisSeriesColors(axisPlot.getRenderer(), fillChart.getPlot());

            if (axisHyperlinkProvider != null) {
                multiHyperlinkProvider.addHyperlinkProvider(axisPlot.getDataset(), axisHyperlinkProvider);
            }
        } else if (mainPlot instanceof XYPlot) {
            XYPlot mainXyPlot = (XYPlot) mainPlot;
            if (!(axisChart.getPlot() instanceof XYPlot)) {
                throw new JRException(EXCEPTION_MESSAGE_KEY_MULTIAXIS_PLOT_TYPES_MIX_NOT_ALLOWED,
                        (Object[]) null);
            }

            // Get the axis and add it to the multi axis chart plot
            XYPlot axisPlot = (XYPlot) axisChart.getPlot();
            mainXyPlot.setRangeAxis(axisNumber, axisPlot.getRangeAxis());
            mainXyPlot.setRangeAxisLocation(axisNumber, getChartAxisLocation(chartAxis));

            // Add the data set and map it to the recently added axis
            mainXyPlot.setDataset(axisNumber, axisPlot.getDataset());
            mainXyPlot.mapDatasetToRangeAxis(axisNumber, axisNumber);

            // Set the renderer to use to draw the dataset.
            mainXyPlot.setRenderer(axisNumber, axisPlot.getRenderer());

            // Handle any color series for this chart
            configureAxisSeriesColors(axisPlot.getRenderer(), fillChart.getPlot());

            if (axisHyperlinkProvider != null) {
                multiHyperlinkProvider.addHyperlinkProvider(axisPlot.getDataset(), axisHyperlinkProvider);
            }
        } else {
            throw new JRException(EXCEPTION_MESSAGE_KEY_MULTIAXIS_PLOT_NOT_SUPPORTED, (Object[]) null);
        }
    }

    //set the multi hyperlink provider
    chartHyperlinkProvider = multiHyperlinkProvider;
}

From source file:mil.tatrc.physiology.utilities.csv.plots.ConvexHullPlotter.java

public void plot(LogListener listener, SESubstanceManager subMgr) {
    //fill PlotJob with needed data if it doesn't exist
    PlotJob job = (PlotJob) listener;//www . j a  v a 2 s .  com
    if (job.dataPath == null || job.dataPath.isEmpty()) {
        job.dataPath = "../verification/Scenarios/" + job.verificationDirectory + "/Current Baseline/";
    }
    if (job.dataFile == null || job.dataFile.isEmpty()) {
        job.dataFile = job.name + "Results.zip";
    }

    //Get data contents for all headers
    if (data.isEmpty() || data == null) {
        try {
            CSVContents csv = new CSVContents(job.dataPath + job.dataFile);
            csv.abbreviateContents = job.resultsSkipNum;
            for (int i = 0; i < job.headers.size(); i++) {
                List<Double> headerData = new ArrayList<Double>();
                csv.readHeader(csv.unitUnderscoreToSpace(job.headers.get(i)), headerData);
                data.put(job.headers.get(i), headerData);
            }
        } catch (IOException e) {
            Log.error("Could not analyze file " + job.dataPath + job.dataFile);
        }
    }

    //Catch some errors
    if (job.Y2headers.size() > 0 && job.X2header == null) {
        Log.error("No X2 header specified for job " + job.name
                + ". Each Y axis must have a corresponding X axis.");
        return;
    }

    //Make a dataSeries for desired headers and add to collection(s)
    CSVPlotTool plotTool = new CSVPlotTool(); //to leverage existing functions
    String title = job.name + "_";
    XYSeriesCollection dataSet1 = new XYSeriesCollection();
    XYSeriesCollection dataSet2 = new XYSeriesCollection();
    double maxY1 = 0;
    double minY1 = Double.MAX_VALUE;
    double maxY2 = 0;
    double minY2 = Double.MAX_VALUE;
    for (int i = 0; i < job.Y1headers.size(); i++) {
        XYSeries dataSeriesTop;
        XYSeries dataSeriesBottom;
        XYSeries dataSeriesLeft;
        XYSeries dataSeriesRight;

        //For convex hulls, we have to reorder points before inserting into the dataset
        ConvexHullMaker maker = new ConvexHullMaker();
        List<List<Double>> newVals = new ArrayList<List<Double>>();
        List<List<Double>> splitVals = new ArrayList<List<Double>>();
        newVals = maker.make(data.get(job.X1header), data.get(job.Y1headers.get(i)));
        splitVals = splitHull(newVals);
        dataSeriesTop = plotTool.createXYSeries(job.Y1headers.get(i), splitVals.get(0), splitVals.get(1));
        dataSeriesBottom = plotTool.createXYSeries("", splitVals.get(2), splitVals.get(3));
        dataSeriesLeft = plotTool.createXYSeries("", splitVals.get(4), splitVals.get(5));
        dataSeriesRight = plotTool.createXYSeries("", splitVals.get(6), splitVals.get(7));

        dataSeriesBottom.setKey("REMOVE");
        dataSeriesLeft.setKey("REMOVE");
        dataSeriesRight.setKey("REMOVE");

        dataSet1.addSeries(dataSeriesTop);
        dataSet1.addSeries(dataSeriesBottom);
        dataSet1.addSeries(dataSeriesLeft);
        dataSet1.addSeries(dataSeriesRight);

        title = title + job.Y1headers.get(i) + "_";
        maxY1 = maxY1 < dataSeriesTop.getMaxY() ? dataSeriesTop.getMaxY() : maxY1;
        minY1 = minY1 > dataSeriesBottom.getMinY() ? dataSeriesBottom.getMinY() : minY1;
    }
    for (int i = 0; i < job.Y2headers.size(); i++) {
        XYSeries dataSeriesTop;
        XYSeries dataSeriesBottom;
        XYSeries dataSeriesLeft;
        XYSeries dataSeriesRight;

        ConvexHullMaker maker = new ConvexHullMaker();
        List<List<Double>> newVals = new ArrayList<List<Double>>();
        List<List<Double>> splitVals = new ArrayList<List<Double>>();
        newVals = maker.make(data.get(job.X2header), data.get(job.Y2headers.get(i)));
        splitVals = splitHull(newVals);
        dataSeriesTop = plotTool.createXYSeries(job.Y2headers.get(i), splitVals.get(0), splitVals.get(1));
        dataSeriesBottom = plotTool.createXYSeries("", splitVals.get(2), splitVals.get(3));
        dataSeriesLeft = plotTool.createXYSeries("", splitVals.get(4), splitVals.get(5));
        dataSeriesRight = plotTool.createXYSeries("", splitVals.get(6), splitVals.get(7));

        dataSeriesBottom.setKey("REMOVE");
        dataSeriesLeft.setKey("REMOVE");
        dataSeriesRight.setKey("REMOVE");

        dataSet2.addSeries(dataSeriesTop);
        dataSet2.addSeries(dataSeriesBottom);
        dataSet2.addSeries(dataSeriesLeft);
        dataSet2.addSeries(dataSeriesRight);

        title = title + job.Y2headers.get(i) + "_";
        maxY2 = maxY2 < dataSeriesTop.getMaxY() ? dataSeriesTop.getMaxY() : maxY2;
        minY2 = minY2 > dataSeriesBottom.getMinY() ? dataSeriesBottom.getMinY() : minY2;
    }
    title = title + "vs_" + job.X1header;
    if (job.X2header != null && !job.X1header.equalsIgnoreCase(job.X2header))
        title = title + "_" + job.X2header;

    //Override the constructed title if desired
    if (job.titleOverride != null && !job.titleOverride.isEmpty()
            && !job.titleOverride.equalsIgnoreCase("None"))
        title = job.titleOverride;

    //set labels
    String XAxisLabel = job.X1header;
    String YAxisLabel = job.Y1headers.get(0);

    JFreeChart chart = ChartFactory.createXYLineChart(
            job.titleOverride != null && job.titleOverride.equalsIgnoreCase("None") ? "" : title, // chart title
            XAxisLabel, // x axis label
            YAxisLabel, // y axis label
            dataSet1, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );

    Log.info("Creating Graph " + title);
    XYPlot plot = (XYPlot) chart.getPlot();

    if (!job.logAxis) {
        // Determine Y1 range
        double resMax0 = maxY1;
        double resMin0 = minY1;
        if (Double.isNaN(resMax0) || Double.isNaN(resMin0))
            plot.getDomainAxis(0).setLabel("Range is NaN");
        if (DoubleUtils.isZero(resMin0))
            resMin0 = -0.001;
        if (DoubleUtils.isZero(resMax0))
            resMax0 = 0.001;
        double rangeLength = resMax0 - resMin0;
        ValueAxis yAxis = plot.getRangeAxis(0);
        yAxis.setRange(resMin0 - 0.15 * rangeLength, resMax0 + 0.15 * rangeLength);//15% buffer so we can see top and bottom clearly  

        //Override the bounds if desired
        try {
            if (job.Y1LowerBound != null)
                yAxis.setLowerBound(job.Y1LowerBound);
            if (job.Y1UpperBound != null)
                yAxis.setUpperBound(job.Y1UpperBound);
        } catch (Exception e) {
            Log.error(
                    "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
        }

        plot.setRangeAxis(0, yAxis);

        //Add the second Y axis to the right side
        if (!job.Y2headers.isEmpty()) {
            ValueAxis rightYAxis = new NumberAxis();
            // Determine Y2 range
            double resMax1 = maxY2;
            double resMin1 = minY2;
            if (Double.isNaN(resMax1) || Double.isNaN(resMin1))
                plot.getDomainAxis(1).setLabel("Range is NaN");
            if (DoubleUtils.isZero(resMin1))
                resMin1 = -0.001;
            if (DoubleUtils.isZero(resMax1))
                resMax1 = 0.001;
            rangeLength = resMax1 - resMin1;
            rightYAxis.setRange(resMin1 - 0.15 * rangeLength, resMax1 + 0.15 * rangeLength);
            rightYAxis.setLabel(job.Y2headers.get(0));

            //Override the bounds if desired
            try {
                if (job.Y2LowerBound != null)
                    rightYAxis.setLowerBound(job.Y2LowerBound);
                if (job.Y2UpperBound != null)
                    rightYAxis.setUpperBound(job.Y2UpperBound);
            } catch (Exception e) {
                Log.error(
                        "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
            }

            plot.setRangeAxis(1, rightYAxis);
        }
    } else {
        double resMin = minY1 < minY2 ? minY1 : minY2;
        if (resMin <= 0.0)
            resMin = .00001;
        LogarithmicAxis yAxis = new LogarithmicAxis("Log(" + YAxisLabel + ")");
        yAxis.setLowerBound(resMin);

        //Override the bounds if desired
        try {
            if (job.Y1LowerBound != null)
                yAxis.setLowerBound(job.Y1LowerBound);
            if (job.Y1UpperBound != null)
                yAxis.setUpperBound(job.Y1UpperBound);
        } catch (Exception e) {
            Log.error(
                    "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
        }

        plot.setRangeAxis(0, yAxis);

        if (!job.Y2headers.isEmpty()) {
            LogarithmicAxis rightYAxis = new LogarithmicAxis("Log(" + job.Y2headers.get(0) + ")");
            rightYAxis.setLowerBound(resMin);

            //Override the bounds if desired
            try {
                if (job.Y2LowerBound != null)
                    rightYAxis.setLowerBound(job.Y2LowerBound);
                if (job.Y2UpperBound != null)
                    rightYAxis.setUpperBound(job.Y2UpperBound);
            } catch (Exception e) {
                Log.error(
                        "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist.");
            }

            plot.setRangeAxis(1, rightYAxis);
        }
    }

    //Override X bounds if desired
    try {
        if (job.X1LowerBound != null)
            plot.getDomainAxis(0).setLowerBound(job.X1LowerBound);
        if (job.X1UpperBound != null)
            plot.getDomainAxis(0).setUpperBound(job.X1UpperBound);
        if (job.X2LowerBound != null)
            plot.getDomainAxis(1).setLowerBound(job.X2LowerBound);
        if (job.X2UpperBound != null)
            plot.getDomainAxis(1).setUpperBound(job.X2UpperBound);
    } catch (Exception e) {
        Log.error("Couldn't set X bounds. You probably tried to set a bound on an axis that doesn't exist.");
    }

    //Add the second dataset if necessary
    if (!job.Y2headers.isEmpty()) {
        plot.setDataset(1, dataSet2);
        plot.mapDatasetToRangeAxis(1, 1);
    }

    //Override labels if desired
    if (job.X1Label != null && !plot.getDomainAxis(0).getLabel().contains("NaN"))
        plot.getDomainAxis(0).setLabel(job.X1Label.equalsIgnoreCase("None") ? "" : job.X1Label);
    if (job.X2Label != null && plot.getDomainAxis(1) != null)
        plot.getDomainAxis(1).setLabel(job.X2Label.equalsIgnoreCase("None") ? "" : job.X2Label);
    if (job.Y1Label != null)
        plot.getRangeAxis(0).setLabel(job.Y1Label.equalsIgnoreCase("None") ? "" : job.Y1Label);
    if (job.Y2Label != null && plot.getRangeAxis(1) != null)
        plot.getRangeAxis(1).setLabel(job.Y2Label.equalsIgnoreCase("None") ? "" : job.Y2Label);

    //Format lines and colors
    plotTool.formatXYPlot(chart, job.bgColor);
    plot.setDomainGridlinesVisible(job.showGridLines);
    plot.setRangeGridlinesVisible(job.showGridLines);
    formatConvexHullPlot(job, chart, dataSet1, dataSet2);

    //Handle legends
    if (job.removeAllLegends)
        chart.removeLegend();

    //Make the file
    try {
        FileUtils.createDirectory(job.outputDir);
        String filename = job.outputFilename == null
                ? job.outputDir + "/" + plotTool.MakeFileName(title) + ".jpg"
                : job.outputDir + "/" + job.outputFilename;
        if (!filename.endsWith(".jpg"))
            filename = filename + ".jpg";
        File JPGFile = new File(filename);
        if (job.imageHeight != null && job.imageWidth != null)
            ChartUtilities.saveChartAsJPEG(JPGFile, chart, job.imageWidth, job.imageHeight);
        else
            ChartUtilities.saveChartAsJPEG(JPGFile, chart, 1600, 800);
    } catch (IOException e) {
        Log.error(e.getMessage());
    }

}