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

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

Introduction

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

Prototype

public void mapDatasetToRangeAxis(int index, int axisIndex) 

Source Link

Document

Maps a dataset to a particular range axis.

Usage

From source file:ucar.unidata.idv.flythrough.ChartDecorator.java

/**
 * _more_//from  w  w  w.j a  v a2s.c  o m
 *
 * @param g2 _more_
 * @param comp _more_
 *
 * @return _more_
 */
public boolean paintDashboard(Graphics2D g2, JComponent comp) {
    try {
        List<SampleInfo> infos = new ArrayList<SampleInfo>(sampleInfos);
        if (infos.size() == 0) {
            return false;
        }
        Rectangle b = comp.getBounds();
        JFrame dummyFrame = new JFrame("");
        XYSeriesCollection dataset = new XYSeriesCollection();
        JFreeChart chart = Flythrough.createChart(dataset);
        XYPlot xyPlot = (XYPlot) chart.getPlot();

        int chartHeight = b.height - flythrough.getDashboardImage().getHeight(null);
        chartHeight = Math.max(chartHeight, 50);
        int chartWidth = Math.min(chartHeight * 4, b.width);

        int dx = b.width / 2 - chartWidth / 2;
        int dy = 0;

        Image lastImage = lastChartImage;
        if ((lastImage != null) && (lastImage.getWidth(null) == chartWidth)
                && (lastImage.getHeight(null) == chartHeight)) {
            g2.translate(dx, dy);
            g2.drawImage(lastImage, 0, 0, null);
            g2.translate(-dx, -dy);
            return false;
        }

        for (int i = 0; i < infos.size(); i++) {
            SampleInfo info = infos.get(i);
            ValueAxis rangeAxis = new NumberAxis(info.getName());
            if (info.getRange() != null) {
                rangeAxis
                        .setRange(new org.jfree.data.Range(info.getRange().getMin(), info.getRange().getMax()));
            }
            dataset = new XYSeriesCollection();
            dataset.addSeries(info.getSeries());
            xyPlot.setRangeAxis(i, rangeAxis, false);
            xyPlot.setDataset(i, dataset);
            xyPlot.mapDatasetToRangeAxis(i, i);
            final Color color = COLORS[i % COLORS.length];
            XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, false) {
                public Paint xgetItemPaint(final int row, final int column) {
                    return color;
                }
            };
            renderer.setSeriesPaint(0, color);
            xyPlot.setRenderer(i, renderer);
        }

        ChartPanel chartPanel = new ChartPanel(chart);
        chartPanel.setPreferredSize(new Dimension(chartWidth, chartHeight));
        dummyFrame.setContentPane(chartPanel);
        dummyFrame.pack();
        Image image = ImageUtils.getImage(chartPanel);
        lastChartImage = image;
        g2.translate(dx, dy);
        g2.drawImage(image, 0, 0, null);
        g2.translate(-dx, -dy);
    } catch (Exception exc) {
        logException("Painting chart", exc);

    }

    return false;

}

From source file:ucar.unidata.idv.control.chart.TimeSeriesChart.java

/**
 * init plot// w  w w.  j a  v a 2  s. c  o  m
 *
 * @param plot plot
 */
protected void initPlot(Plot plot) {
    XYPlot xyPlot = (XYPlot) plot;
    int count = xyPlot.getDatasetCount();
    for (int i = 0; i < count; i++) {
        xyPlot.setDataset(i, null);
        xyPlot.setRenderer(i, null);
    }
    xyPlot.clearRangeAxes();
    XYDataset dummyDataset = getDummyDataset();
    ValueAxis rangeAxis = new FixedWidthNumberAxis();
    xyPlot.setRangeAxis(0, rangeAxis, false);
    xyPlot.setDataset(0, dummyDataset);
    xyPlot.mapDatasetToRangeAxis(0, 0);
    xyPlot.setRenderer(0, new XYLineAndShapeRenderer());
}

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

protected JFreeChart renderPreChart(Map<String, OXFFeatureCollection> entireCollMap,
        String[] observedProperties, ArrayList<TimeSeriesCollection> timeSeries, Calendar begin, Calendar end) {

    JFreeChart chart = ChartFactory.createTimeSeriesChart(null, // title
            "Date", // x-axis label
            observedProperties[0], // y-axis label
            timeSeries.get(0), // data
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
    );/*from   w ww.  j a  v  a 2s .  c om*/

    chart.setBackgroundPaint(Color.white);

    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);
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setBaseShapesVisible(true);
    renderer.setBaseShapesFilled(true);

    // add additional datasets:
    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setRange(begin.getTime(), end.getTime());
    axis.setDateFormatOverride(new SimpleDateFormat());
    for (int i = 1; i < observedProperties.length; i++) {
        XYDataset additionalDataset = timeSeries.get(i);
        plot.setDataset(i, additionalDataset);
        plot.setRangeAxis(i, new NumberAxis(observedProperties[i]));
        // plot.getRangeAxis(i).setRange((Double)
        // overAllSeriesCollection.getMinimum(i),
        // (Double) overAllSeriesCollection.getMaximum(i));
        plot.mapDatasetToRangeAxis(i, i);
        // plot.getDataset().getXValue(i, i);
    }
    return chart;
}

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/* www .  j  av a2s.com*/
 * @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:org.n52.server.io.render.DiagramRenderer.java

protected JFreeChart renderPreChart(Map<String, OXFFeatureCollection> entireCollMap,
        String[] observedProperties, ArrayList<TimeSeriesCollection> timeSeries, Calendar begin, Calendar end) {

    JFreeChart chart = ChartFactory.createTimeSeriesChart(null, // title
            "Date", // x-axis label
            observedProperties[0], // y-axis label
            timeSeries.get(0), // data
            true, // create legend?
            true, // generate tooltips?
            false // generate URLs?
    );//from  w  ww .  j  ava2  s. c o m

    chart.setBackgroundPaint(Color.white);

    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);
    XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
    renderer.setBaseShapesVisible(true);
    renderer.setBaseShapesFilled(true);

    // add additional datasets:
    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setRange(begin.getTime(), end.getTime());
    axis.setDateFormatOverride(new SimpleDateFormat());
    axis.setTimeZone(end.getTimeZone());
    for (int i = 1; i < observedProperties.length; i++) {
        XYDataset additionalDataset = timeSeries.get(i);
        plot.setDataset(i, additionalDataset);
        plot.setRangeAxis(i, new NumberAxis(observedProperties[i]));
        // plot.getRangeAxis(i).setRange((Double)
        // overAllSeriesCollection.getMinimum(i),
        // (Double) overAllSeriesCollection.getMaximum(i));
        plot.mapDatasetToRangeAxis(i, i);
        // plot.getDataset().getXValue(i, i);
    }
    return chart;
}

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  . ja  v a 2  s. co  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: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 . ja  v  a2 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.LogLinChartUIComponent.java

/***********************************************************************************************
 * Customise the XYPlot of a new chart, e.g. for fixed range axes.
 *
 * @param datasettype/*from  w  ww  . j  a va  2s.c o  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:fmiquerytest.Coordinates.java

static String drawTempRainChart(List<stepWeather> stepDataBase, Map routeWeather) {
    //First, fetch the real data
    List<Double> times = new ArrayList<>();
    List<Double> temps = new ArrayList<>();
    List<Double> rains = new ArrayList<>();
    List<Double> lights = new ArrayList<>();
    for (int i = 0; i < stepDataBase.size(); ++i) {
        stepWeather step = stepDataBase.get(i);
        stepWeather nextstep = step;//from ww w. j av  a  2  s .c o  m
        if (i < stepDataBase.size() - 1) {
            nextstep = stepDataBase.get(i + 1);
        }
        times.add(step.timeAsDouble);
        temps.add(getParameterAverage(routeWeather, step, nextstep, "Temperature"));
        rains.add(getParameterAverage(routeWeather, step, nextstep, "Precipitation1h"));
        lights.add(Math.pow(Math.abs(step.timeAsDouble % 24 - ((step.sunRise + step.sunSet) / 2))
                / ((step.sunSet - step.sunRise) / 2), 5));
    }

    double zeroPoint = times.get(0);
    // Make first dataset
    final TimeSeriesCollection dataset = new TimeSeriesCollection();
    final TimeSeries s1 = new TimeSeries("Temperature C", Minute.class);
    // Make second dataset
    final TimeSeriesCollection dataset2 = new TimeSeriesCollection();
    final TimeSeries s2 = new TimeSeries("Rain (mm)", Minute.class);
    // Make third dataset
    //final TimeSeriesCollection dataset3 = new TimeSeriesCollection();
    final TimeSeries s3 = new TimeSeries("Darkness", Minute.class);
    // Show data per minute
    RegularTimePeriod start = new Minute(new Date(FmiQueryTest.startTimeMillis));
    for (int i = 0; i < times.size() - 1; ++i) {
        double time = times.get(i);
        double nexttime = times.get(i + 1);
        int firstMinute = intValue((time - zeroPoint) * 60);
        int currentMinute = firstMinute;
        int lastMinute = intValue((nexttime - zeroPoint) * 60);
        while (currentMinute < lastMinute) {
            s1.add(start, temps.get(i) + ((double) currentMinute - firstMinute) / (lastMinute - firstMinute)
                    * (temps.get(i + 1) - temps.get(i)));
            s2.add(start, (rains.get(i) + rains.get(i + 1)) / 2);
            //+((double)currentMinute-firstMinute)/(lastMinute-firstMinute)*(rains.get(i+1)-rains.get(i)));
            s3.add(start, lights.get(i) + ((double) currentMinute - firstMinute) / (lastMinute - firstMinute)
                    * (lights.get(i + 1) - lights.get(i)));
            ++currentMinute;
            start = start.next();
        }
    }
    dataset.addSeries(s1);
    dataset2.addSeries(s3);
    dataset2.addSeries(s2);

    // Initialize chart
    final JFreeChart chart = ChartFactory.createTimeSeriesChart("Temperature and rain", "Time",
            "Temperature C", dataset, true, // legend? 
            true, // tooltips? 
            false // URLs? 
    );
    final XYPlot plot = chart.getXYPlot();
    plot.getDomainAxis().setLowerMargin(0.0);
    plot.getDomainAxis().setUpperMargin(0.0);

    // configure the range axis to display first dataset...
    final ValueAxis rangeAxis = (ValueAxis) plot.getRangeAxis();
    rangeAxis.setRange(-30, 30);
    final TickUnits units = new TickUnits();
    units.add(new NumberTickUnit(10.0));
    units.add(new NumberTickUnit(1.0));
    units.add(new NumberTickUnit(0.1));
    rangeAxis.setStandardTickUnits(units);
    //rangeAxis.setTickLabelFont(new Font("SansSerif", Font.BOLD, 16));

    // add the secondary dataset/renderer/axis
    plot.setRangeAxis(rangeAxis);
    final XYItemRenderer renderer2 = new XYAreaRenderer();
    final ValueAxis axis2 = new NumberAxis("Rain (mm) ");
    axis2.setRange(0, 2);
    axis2.setStandardTickUnits(units);
    //axis2.setTickLabelFont(new Font("SansSerif", Font.BOLD, 16));
    renderer2.setSeriesPaint(0, new Color(0, 0, 255, 128));
    plot.setDataset(1, dataset2);
    plot.setRenderer(1, renderer2);
    plot.setRangeAxis(1, axis2);
    plot.mapDatasetToRangeAxis(1, 1);
    final XYItemRenderer renderer3 = new XYAreaRenderer();
    renderer3.setSeriesPaint(0, new Color(0, 0, 0, 64));
    //plot.setDataset(1, dataset2);
    plot.setRenderer(1, renderer3);
    plot.setRangeAxis(1, axis2);
    plot.mapDatasetToRangeAxis(1, 1);

    chart.setBackgroundPaint(Color.white);
    //plot.setBackgroundPaint(Color.lightGray);
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(Color.black);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.black);

    //        final TextTitle subtitle = new TextTitle("An area chart demonstration.  We use this "
    //            + "subtitle as an example of what happens when you get a really long title or "
    //            + "subtitle.");
    //        subtitle.setFont(new Font("SansSerif", Font.PLAIN, 12));
    //        subtitle.setPosition(RectangleEdge.TOP);
    ////        subtitle.setSpacer(new Spacer(Spacer.RELATIVE, 0.05, 0.05, 0.05, 0.05));
    //        subtitle.setVerticalAlignment(VerticalAlignment.BOTTOM);
    //        chart.addSubtitle(subtitle);

    // Produce chart
    //        ChartFrame frame = new ChartFrame("Tamperature and rain", chart);
    //        frame.pack();
    //        RefineryUtilities.centerFrameOnScreen(frame);
    //        frame.setVisible(true);
    ByteArrayOutputStream bas = new ByteArrayOutputStream();
    try {
        ChartUtilities.writeChartAsPNG(bas, chart, 600, 400);
    } catch (IOException ex) {
        Logger.getLogger(WeatherTools.class.getName()).log(Level.SEVERE, null, ex);
    }
    byte[] byteArray = bas.toByteArray();
    String baseCode = Base64.encode(byteArray);
    return "<img width=\"480\" alt=\"Temperature and rain\" src=\"data:image/png;base64," + baseCode.trim()
            + "\" />";
}

From source file:dk.netarkivet.harvester.harvesting.monitor.StartedJobHistoryChartGen.java

/**
 * Generates a chart in PNG format./*from  w  w  w  .  j  a  v a2  s.c om*/
 * @param outputFile the output file, it should exist.
 * @param pxWidth the image width in pixels.
 * @param pxHeight the image height in pixels.
 * @param chartTitle the chart title, may be null.
 * @param xAxisTitle the x axis title
 * @param yDataSeriesRange the axis range (null for auto)
 * @param yDataSeriesTitles the Y axis titles.
 * @param timeValuesInSeconds the time values in seconds
 * @param yDataSeries the Y axis value series.
 * @param yDataSeriesColors the Y axis value series drawing colors.
 * @param yDataSeriesTickSuffix TODO explain argument yDataSeriesTickSuffix
 * @param drawBorder draw, or not, the border.
 * @param backgroundColor the chart background color.
 */
final void generatePngChart(File outputFile, int pxWidth, int pxHeight, String chartTitle, String xAxisTitle,
        String[] yDataSeriesTitles, double[] timeValuesInSeconds, double[][] yDataSeriesRange,
        double[][] yDataSeries, Color[] yDataSeriesColors, String[] yDataSeriesTickSuffix, boolean drawBorder,
        Color backgroundColor) {

    // Domain axis
    NumberAxis xAxis = new NumberAxis(xAxisTitle);
    xAxis.setFixedDimension(CHART_AXIS_DIMENSION);
    xAxis.setLabelPaint(Color.black);
    xAxis.setTickLabelPaint(Color.black);

    double maxSeconds = getMaxValue(timeValuesInSeconds);
    TimeAxisResolution xAxisRes = TimeAxisResolution.findTimeUnit(maxSeconds);
    xAxis.setTickUnit(new NumberTickUnit(xAxisRes.tickStep));
    double[] scaledTimeValues = xAxisRes.scale(timeValuesInSeconds);

    String tickSymbol = I18N.getString(locale, "running.job.details.chart.timeunit.symbol." + xAxisRes.name());
    xAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + tickSymbol + "'"));

    // First dataset
    String firstDataSetTitle = yDataSeriesTitles[0];
    XYDataset firstDataSet = createXYDataSet(firstDataSetTitle, scaledTimeValues, yDataSeries[0]);
    Color firstDataSetColor = yDataSeriesColors[0];

    // First range axis
    NumberAxis firstYAxis = new NumberAxis(firstDataSetTitle);

    firstYAxis.setFixedDimension(CHART_AXIS_DIMENSION);
    setAxisRange(firstYAxis, yDataSeriesRange[0]);
    firstYAxis.setLabelPaint(firstDataSetColor);
    firstYAxis.setTickLabelPaint(firstDataSetColor);
    String firstAxisTickSuffix = yDataSeriesTickSuffix[0];
    if (firstAxisTickSuffix != null && !firstAxisTickSuffix.isEmpty()) {
        firstYAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + firstAxisTickSuffix + "'"));
    }

    // Create the plot with domain axis and first range axis
    XYPlot plot = new XYPlot(firstDataSet, xAxis, firstYAxis, null);

    XYLineAndShapeRenderer firstRenderer = new XYLineAndShapeRenderer(true, false);
    plot.setRenderer(firstRenderer);

    plot.setOrientation(PlotOrientation.VERTICAL);
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);

    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    firstRenderer.setSeriesPaint(0, firstDataSetColor);

    // Now iterate on next axes
    for (int i = 1; i < yDataSeries.length; i++) {
        // Create axis
        String seriesTitle = yDataSeriesTitles[i];
        Color seriesColor = yDataSeriesColors[i];
        NumberAxis yAxis = new NumberAxis(seriesTitle);

        yAxis.setFixedDimension(CHART_AXIS_DIMENSION);
        setAxisRange(yAxis, yDataSeriesRange[i]);

        yAxis.setLabelPaint(seriesColor);
        yAxis.setTickLabelPaint(seriesColor);

        String yAxisTickSuffix = yDataSeriesTickSuffix[i];
        if (yAxisTickSuffix != null && !yAxisTickSuffix.isEmpty()) {
            yAxis.setNumberFormatOverride(new DecimalFormat("###.##'" + yAxisTickSuffix + "'"));
        }

        // Create dataset and add axis to plot
        plot.setRangeAxis(i, yAxis);
        plot.setRangeAxisLocation(i, AxisLocation.BOTTOM_OR_LEFT);
        plot.setDataset(i, createXYDataSet(seriesTitle, scaledTimeValues, yDataSeries[i]));
        plot.mapDatasetToRangeAxis(i, i);
        XYItemRenderer renderer = new StandardXYItemRenderer();
        renderer.setSeriesPaint(0, seriesColor);
        plot.setRenderer(i, renderer);
    }

    // Create the chart
    JFreeChart chart = new JFreeChart(chartTitle, JFreeChart.DEFAULT_TITLE_FONT, plot, false);

    // Customize rendering
    chart.setBackgroundPaint(Color.white);
    chart.setBorderVisible(true);
    chart.setBorderPaint(Color.BLACK);

    // Render image
    try {
        ChartUtilities.saveChartAsPNG(outputFile, chart, pxWidth, pxHeight);
    } catch (IOException e) {
        LOG.error("Chart export failed", e);
    }
}