Example usage for org.jfree.chart.axis NumberTickUnit NumberTickUnit

List of usage examples for org.jfree.chart.axis NumberTickUnit NumberTickUnit

Introduction

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

Prototype

public NumberTickUnit(double size) 

Source Link

Document

Creates a new number tick unit.

Usage

From source file:netplot.GenericPlotPanel.java

void genericConfig(JFreeChart chart, XYPlot plot, int plotIndex) {
    if (!enableLegend) {
        chart.removeLegend();/* w  w  w  .j  a  v a2s .c  o  m*/
    }

    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:piilSource.BarChart.java

private JFreeChart createChart(String title, final CategoryDataset dataset, String metaLabel) {

    // create the chart...
    final JFreeChart chart = ChartFactory.createBarChart(
            "Barplot of the " + metaLabel + " values for all samples - " + title, // chart title
            "Samples", // domain axis label
            metaLabel + " values", // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips?
            false // URLs?
    );/*from  www.j  a  v a  2  s. c o m*/

    // set the background color for the chart...
    chart.setBackgroundPaint(Color.white);

    // get a reference to the plot for further customisation...
    final CategoryPlot plot = chart.getCategoryPlot();
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.red);
    plot.setRangeGridlinePaint(Color.white);

    // set the range axis to display integers only...
    final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    if (metaLabel.equals("beta")) {
        rangeAxis.setRange(0, 1);
        rangeAxis.setTickUnit(new NumberTickUnit(0.2));
    }

    // disable bar outlines...
    final BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(false);

    // set up gradient paints for series...
    final GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.blue, 0.0f, 0.0f, Color.blue);
    final GradientPaint gp1 = new GradientPaint(0.0f, 0.0f, Color.green, 0.0f, 0.0f, Color.green);
    final GradientPaint gp2 = new GradientPaint(0.0f, 0.0f, Color.red, 0.0f, 0.0f, Color.red);
    final GradientPaint gp3 = new GradientPaint(0.0f, 0.0f, Color.yellow, 0.0f, 0.0f, Color.yellow);
    final GradientPaint gp4 = new GradientPaint(0.0f, 0.0f, Color.cyan, 0.0f, 0.0f, Color.cyan);
    renderer.setSeriesPaint(0, gp0);
    renderer.setSeriesPaint(1, gp1);
    renderer.setSeriesPaint(2, gp2);
    renderer.setSeriesPaint(3, gp3);
    renderer.setSeriesPaint(4, gp4);

    final CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));
    if (dataset.getColumnCount() > 40) {
        domainAxis.setTickLabelFont(new Font("Serif", Font.PLAIN, 10));
        domainAxis
                .setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 2));
    }
    return chart;
}

From source file:replicatorg.app.ui.panels.ControlPanel.java

private ChartPanel makeChart() {
    JFreeChart chart = ChartFactory.createXYLineChart(null, null, null, t0MeasuredDataset,
            PlotOrientation.VERTICAL, false, false, false);
    chart.setBorderVisible(false);//from   w  ww . j  av  a  2s  . c  o  m
    chart.setBackgroundPaint(null);

    XYPlot plot = chart.getXYPlot();
    ValueAxis axis = plot.getDomainAxis();
    axis.setLowerMargin(0);
    axis.setFixedAutoRange(3L * 60L * 1000L); // auto range to three minutes

    TickUnits unitSource = new TickUnits();
    unitSource.add(new NumberTickUnit(60L * 1000L)); // minutes
    unitSource.add(new NumberTickUnit(1L * 1000L)); // seconds

    axis.setStandardTickUnits(unitSource);
    axis.setTickLabelsVisible(false); // We don't need to see the millisecond count
    axis = plot.getRangeAxis();
    axis.setRange(0, 300); // set temperature range from 0 to 300 degrees C so you can see overshoots 

    XYStepRenderer renderer = new XYStepRenderer();
    plot.setDataset(1, t0TargetDataset);
    plot.setRenderer(1, renderer);
    plot.getRenderer(1).setSeriesPaint(0, t0TargetColor);
    plot.getRenderer(0).setSeriesPaint(0, t0MeasuredColor);

    plot.setDataset(2, pMeasuredDataset);
    plot.setRenderer(2, new XYLineAndShapeRenderer(true, false));
    plot.getRenderer(2).setSeriesPaint(0, pMeasuredColor);
    plot.setDataset(3, pTargetDataset);
    plot.setRenderer(3, new XYStepRenderer());
    plot.getRenderer(3).setSeriesPaint(0, pTargetColor);

    plot.setDatasetRenderingOrder(DatasetRenderingOrder.REVERSE);
    ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new Dimension(400, 160));
    chartPanel.setOpaque(false);
    return chartPanel;
}

From source file:edu.umn.ecology.populus.plot.BasicPlotInfo.java

public ChartTheme getJFreeChartTheme() {
    class PopChartTheme implements ChartTheme {
        private BasicPlotInfo bpiRef;

        public PopChartTheme(BasicPlotInfo bpi) {
            this.bpiRef = bpi;
        }//w w  w  .  j a  va  2  s.  co  m

        public void apply(JFreeChart chart) {
            JFCXYAdapter jfca = new JFCXYAdapter();
            XYPlot plot = chart.getXYPlot();
            plot.setDataset(jfca);

            if (isLogPlot) {
                plot.setRangeAxis(new LogarithmicAxis(""));
            }
            if (isFrequencies) {
                ValueAxis va = plot.getRangeAxis();
                if (va instanceof NumberAxis) {
                    NumberAxis na = (NumberAxis) va;
                    na.setTickUnit(new NumberTickUnit(0.1));
                } else {
                    Logging.log("Range Axis is not NumberAxis, why?", Logging.kWarn);
                }
            }

            if (xMinSet)
                plot.getDomainAxis().setLowerBound(xAxisMin);
            if (xMaxSet)
                plot.getDomainAxis().setUpperBound(xAxisMax);
            if (yMinSet)
                plot.getRangeAxis().setLowerBound(yAxisMin);
            if (yMaxSet)
                plot.getRangeAxis().setUpperBound(yAxisMax);

            //TODO - just use this renderer
            plot.setRenderer(new ChartRendererWithOrientatedShapes(bpiRef));

            XYItemRenderer r = plot.getRenderer();
            //         AbstractXYItemRenderer r = plot.getRenderer();
            if (r instanceof XYLineAndShapeRenderer) {
                XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
                for (int i = 0; i < getNumSeries(); i++) {
                    //Set Line
                    renderer.setSeriesPaint(i, getLineColor(i));
                    renderer.setSeriesStroke(i, getLineStroke(i));

                    //Set Symbol
                    renderer.setSeriesFillPaint(i, getSymbolColor(i));
                    renderer.setSeriesOutlinePaint(i, getSymbolColor(i));

                    Shape shape = getSymbolShape(i);
                    if (shape != null) {
                        renderer.setSeriesShape(i, shape);
                        renderer.setSeriesShapesFilled(i, isSymbolOpaque(i));
                        renderer.setUseFillPaint(true);
                        renderer.setUseOutlinePaint(true);
                        renderer.setSeriesShapesVisible(i, true);
                    }
                }
            } else if (r instanceof XYBarRenderer) {
                XYBarRenderer barRenderer = (XYBarRenderer) r;
                barRenderer.setBarPainter(new StandardXYBarPainter());
            } else {
                Logging.log("Unknown renderer type: " + r.getClass(), Logging.kWarn);
            }

            //inner labels, used in AIDS: Therapy
            plot.clearAnnotations();
            Enumeration<InnerLabel> e = innerLabels.elements();
            while (e.hasMoreElements()) {
                InnerLabel lab = (InnerLabel) e.nextElement();
                Logging.log("Adding " + lab.caption + " at " + lab.x + ", " + lab.y);

                XYTextAnnotation annotation = new XYTextAnnotation(lab.caption, lab.x, lab.y);
                annotation.setTextAnchor(TextAnchor.BOTTOM_CENTER);
                annotation.setOutlineVisible(true);
                plot.addAnnotation(annotation);

                //I actually think the annotation above is ugly.  We can use one of these instead in the future, maybe...
                /*PointerAnnotation may look cool...
                 * That 2.0 is the angle, randomly picked
                 * XYPointerAnnotation annotation = new XYPointerAnnotation(lab.caption, lab.x, lab.y, 2.0); 
                 */

                /*
                ValueMarker marker = new ValueMarker(lab.x);
                marker.setLabel(lab.caption);
                marker.setLabelAnchor(RectangleAnchor.BOTTOM_LEFT);
                plot.addDomainMarker(marker);
                 */

            }

            //This is set for GD: AMCM
            if (startGridded) {
                plot.setDomainGridlinesVisible(true);
                plot.setDomainGridlinePaint(Color.BLACK);
                plot.setRangeGridlinesVisible(true);
                plot.setRangeGridlinePaint(Color.BLACK);
            }

        }
    }
    return new PopChartTheme(this);
}

From source file:eu.cassandra.training.utils.ChartUtils.java

/**
 * This function is used for the visualization of two Area Diagrams.
 * /*  ww  w .  ja  v a2  s . c o  m*/
 * @param title
 *          The title of the chart.
 * @param x
 *          The unit on the X axis of the chart.
 * @param y
 *          The unit on the Y axis of the chart.
 * @param doubles
 *          The array of values of the first array.
 * 
 * @return a chart panel with the graphical representation.
 */
public static ChartPanel createExpectedPowerChart(String title, String x, String y, double[] data) {
    JFreeChart chart = null;

    XYSeries series1 = new XYSeries("Expected Power");
    for (int i = 0; i < data.length; i++) {
        series1.add(i, data[i]);
    }

    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(series1);

    PlotOrientation orientation = PlotOrientation.VERTICAL;
    boolean show = false;
    boolean toolTips = false;
    boolean urls = false;

    chart = ChartFactory.createXYLineChart(title, x, y, dataset, orientation, show, toolTips, urls);

    chart.setBackgroundPaint(Color.white);

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis();
    domainAxis.setVerticalTickLabels(true);
    domainAxis.setRange(0.0, 1440.0);
    domainAxis.setTickUnit(new NumberTickUnit(100));

    return new ChartPanel(chart);
}

From source file:ec.ui.view.DistributionView.java

private static JFreeChart createDistributionViewChart() {
    XYPlot plot = new XYPlot();

    XYLineAndShapeRenderer dRenderer = new XYSplineRenderer();
    dRenderer.setBaseShapesVisible(false);
    dRenderer.setAutoPopulateSeriesPaint(false);
    dRenderer.setAutoPopulateSeriesStroke(false);
    dRenderer.setBaseStroke(TsCharts.getStrongStroke(LinesThickness.Thin));
    dRenderer.setDrawSeriesLineAsPath(true); // not sure if useful
    plot.setDataset(DISTRIBUTION_INDEX, Charts.emptyXYDataset());
    plot.setRenderer(DISTRIBUTION_INDEX, dRenderer);

    XYBarRenderer hRenderer = new XYBarRenderer();
    hRenderer.setShadowVisible(false);//  w w  w.j a  va2s.  c om
    hRenderer.setDrawBarOutline(true);
    hRenderer.setAutoPopulateSeriesPaint(false);
    hRenderer.setAutoPopulateSeriesOutlinePaint(false);
    hRenderer.setBaseSeriesVisibleInLegend(false);
    plot.setDataset(HISTOGRAM_INDEX, Charts.emptyXYDataset());
    plot.setRenderer(HISTOGRAM_INDEX, hRenderer);

    NumberAxis domainAxis = new NumberAxis();
    domainAxis.setTickLabelPaint(TsCharts.CHART_TICK_LABEL_COLOR);
    plot.setDomainAxis(domainAxis);
    plot.setDomainGridlinesVisible(false);

    NumberAxis rangeAxis = new NumberAxis();
    rangeAxis.setTickLabelPaint(TsCharts.CHART_TICK_LABEL_COLOR);
    rangeAxis.setTickUnit(new NumberTickUnit(0.05));
    rangeAxis.setNumberFormatOverride(new DecimalFormat("0.###"));
    plot.setRangeAxis(rangeAxis);

    plot.mapDatasetToDomainAxis(0, 0);
    plot.mapDatasetToRangeAxis(0, 0);
    plot.mapDatasetToDomainAxis(1, 0);
    plot.mapDatasetToRangeAxis(1, 0);

    JFreeChart result = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    result.setPadding(TsCharts.CHART_PADDING);
    result.getTitle().setFont(TsCharts.CHART_TITLE_FONT);
    result.getLegend().setFrame(BlockBorder.NONE);
    result.getLegend().setBackgroundPaint(null);
    return result;
}

From source file:asl.util.PlotMaker.java

public void plotPSD(double per[], double[] model, double[] nhnmPer, double[] nhnm, double[] psd,
        String modelName, String plotString) {

    // plotTitle = "2012074.IU_ANMO.00-BHZ " + plotString
    final String plotTitle = String.format("%04d%03d.%s.%s %s", date.get(Calendar.YEAR),
            date.get(Calendar.DAY_OF_YEAR), station, channel, plotString);
    // plot filename = "2012074.IU_ANMO.00-BHZ" + plotString + ".png"
    final String pngName = String.format("%s/%04d%03d.%s.%s.%s.png", outputDir, date.get(Calendar.YEAR),
            date.get(Calendar.DAY_OF_YEAR), station, channel, plotString);
    File outputFile = new File(pngName);

    // Check that we will be able to output the file without problems and if not --> return
    if (!checkFileOut(outputFile)) {
        System.out.format(/*from ww w.j  av a 2s  . com*/
                "== plotPSD: request to output plot=[%s] but we are unable to create it " + " --> skip plot\n",
                pngName);
        return;
    }

    Boolean plotNHNM = false;
    //if (nhnm.length > 0) {
    if (nhnm != null) {
        plotNHNM = true;
    }

    final XYSeries series1 = new XYSeries(modelName);
    final XYSeries series2 = new XYSeries(channel.toString());
    final XYSeries series3 = new XYSeries("NHNM");

    for (int k = 0; k < per.length; k++) {
        series1.add(per[k], model[k]);
        series2.add(per[k], psd[k]);
    }

    if (plotNHNM) {
        for (int k = 0; k < nhnmPer.length; k++) {
            series3.add(nhnmPer[k], nhnm[k]);
        }
    }

    //final XYItemRenderer renderer = new StandardXYItemRenderer();
    final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    Rectangle rectangle = new Rectangle(3, 3);

    renderer.setSeriesShape(0, rectangle);
    renderer.setSeriesShapesVisible(0, false);
    renderer.setSeriesLinesVisible(0, true);

    renderer.setSeriesShape(1, rectangle);
    renderer.setSeriesShapesVisible(1, true);
    renderer.setSeriesLinesVisible(1, false);

    renderer.setSeriesShape(2, rectangle);
    renderer.setSeriesShapesVisible(2, false);
    renderer.setSeriesLinesVisible(2, true);

    Paint[] paints = new Paint[] { Color.blue, Color.red, Color.black };
    renderer.setSeriesPaint(0, paints[0]);
    renderer.setSeriesPaint(1, paints[1]);
    renderer.setSeriesPaint(2, paints[2]);

    final NumberAxis rangeAxis1 = new NumberAxis("PSD 10log10(m**2/s**4)/Hz dB");
    //rangeAxis1.setRange( new Range(-190, -120));
    rangeAxis1.setRange(new Range(-190, -95));
    rangeAxis1.setTickUnit(new NumberTickUnit(5.0));

    final LogarithmicAxis horizontalAxis = new LogarithmicAxis("Period (sec)");
    horizontalAxis.setRange(new Range(0.05, 10000));

    final XYSeriesCollection seriesCollection = new XYSeriesCollection();
    seriesCollection.addSeries(series1);
    seriesCollection.addSeries(series2);

    if (plotNHNM) {
        seriesCollection.addSeries(series3);
    }

    final XYPlot xyplot = new XYPlot((XYDataset) seriesCollection, horizontalAxis, rangeAxis1, renderer);

    xyplot.setDomainGridlinesVisible(true);
    xyplot.setRangeGridlinesVisible(true);
    xyplot.setRangeGridlinePaint(Color.black);
    xyplot.setDomainGridlinePaint(Color.black);

    final JFreeChart chart = new JFreeChart(xyplot);
    chart.setTitle(new TextTitle(plotTitle));

    try {
        ChartUtilities.saveChartAsPNG(outputFile, chart, 500, 300);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");

    }
}

From source file:stockit.allStocks.java

private void stockPerfmActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stockPerfmActionPerformed
    // TODO add your handling code here:
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    int row = table.getSelectedRow();
    if (row != -1) {
        //dataset.setValue(, "", table.getValueAt(0,1).toString());
        String selectedStock = table.getValueAt(row, 0).toString();
        try {// w  w  w . j a v a2s . c o m
            DBConnection dbcon = new DBConnection();
            dbcon.establishConnection();
            Statement stmt = dbcon.con.createStatement();
            ResultSet rs = stmt
                    .executeQuery("Select stock_daily_performance.Closing_Price, stock_daily_performance.Date\n"
                            + "FROM stock_daily_performance, stock\n"
                            + "WHERE stock_daily_performance.StockID = stock.StockID AND stock.StockID = '"
                            + selectedStock + "'" + "AND Date IN\n" + "( Select * from\n" + "(\n"
                            + "SELECT Date \n" + "FROM stock_daily_performance \n"
                            + "WHERE StockID = stockID \n" + "ORDER BY Date ASC\n" + ") temp_table)\n"
                            + "            ");

            while (rs.next()) {

                String formattedDate = rs.getString("Date");
                int closing_price = rs.getInt("Closing_Price");
                System.out.println("Closing Price: " + closing_price);
                System.out.println("Date: " + formattedDate);
                dataset.setValue(closing_price, "value", formattedDate);

            }
            dbcon.con.close();
        } catch (Exception ex) {
            Logger.getLogger(clientLogin.class.getName()).log(Level.SEVERE, null, ex);
        }
        String stockName = table.getValueAt(row, 1).toString();
        JFreeChart chart = ChartFactory.createLineChart(stockName + " Stock Performance", "Date", "Value",
                dataset, PlotOrientation.VERTICAL, false, false, false);
        Color c = new Color(240, 240, 240, 0);
        chart.setBackgroundPaint(c);
        CategoryPlot catPlot = chart.getCategoryPlot();
        catPlot.setRangeGridlinePaint(Color.BLACK);
        //set interval of Y-axis ticks (tick every 5 units)
        NumberAxis yAxis = (NumberAxis) catPlot.getRangeAxis();
        yAxis.setTickUnit(new NumberTickUnit(5));

        //set y-axis labels as currency types ($)
        NumberFormat currency = NumberFormat.getCurrencyInstance();
        yAxis.setNumberFormatOverride(currency);

        //setting number of lines an x-axis label is displayed on
        CategoryAxis categoryAxis = catPlot.getDomainAxis();
        categoryAxis.setMaximumCategoryLabelLines(4);
        graphPanel.setLayout(new java.awt.BorderLayout());
        ChartPanel chartPanel = new ChartPanel(chart);
        graphPanel.removeAll();
        graphPanel.add(chartPanel, BorderLayout.CENTER);
        graphPanel.validate();
        graphPanel.repaint();
    }
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/**
 * Generates a chart in PNG format./*from   w  w w .  j  a  v  a2 s  .c  o m*/
 * @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);
    }
}