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

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

Introduction

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

Prototype

public void setTickUnit(NumberTickUnit unit) 

Source Link

Document

Sets the tick unit for the axis and sends an AxisChangeEvent to all registered listeners.

Usage

From source file:netplot.GenericPlotPanel.java

void genericConfig(JFreeChart chart, XYPlot plot, int plotIndex) {
    if (!enableLegend) {
        chart.removeLegend();/*  www  . ja v a  2  s  . co  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:asl.plotmaker.PlotMaker2.java

public void writePlot(String fileName) {
    // System.out.format("== plotTitle=[%s] fileName=[%s]\n", plotTitle,
    // fileName);

    File outputFile = new File(fileName);

    // Check that we will be able to output the file without problems and if
    // not --> return
    if (!checkFileOut(outputFile)) {
        // System.out.format("== plotMaker: request to output plot=[%s] but we are unable to create it "
        // + " --> skip plot\n", fileName );
        logger.warn("== Request to output plot=[{}] but we are unable to create it " + " --> skip plot\n",
                fileName);//from  www .  ja  va 2  s  . c o  m
        return;
    }

    NumberAxis horizontalAxis = new NumberAxis("x-axis default"); // x =
    // domain

    if (fileName.contains("alnm") || fileName.contains("nlnm") || fileName.contains("coher")
            || fileName.contains("stn")) { // NLNM or StationDeviation
        horizontalAxis = new LogarithmicAxis("Period (sec)");
        horizontalAxis.setRange(new Range(1, 11000));
        horizontalAxis.setTickUnit(new NumberTickUnit(5.0));
    } else { // EventCompareSynthetics/StrongMotion
        horizontalAxis = new NumberAxis("Time (s)");
        double x[] = panels.get(0).getTraces().get(0).getxData();
        horizontalAxis.setRange(new Range(x[0], x[x.length - 1]));
    }

    CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(horizontalAxis);
    combinedPlot.setGap(15.);

    // Loop over (3) panels for this plot:

    for (Panel panel : panels) {

        NumberAxis verticalAxis = new NumberAxis("y-axis default"); // y =
        // range

        if (fileName.contains("alnm") || fileName.contains("nlnm") || fileName.contains("stn")) { // NLNM
            // or
            // StationDeviation
            verticalAxis = new NumberAxis("PSD 10log10(m**2/s**4)/Hz dB");
            verticalAxis.setRange(new Range(-190, -80));
            verticalAxis.setTickUnit(new NumberTickUnit(5.0));
        } else if (fileName.contains("coher")) { // Coherence
            verticalAxis = new NumberAxis("Coherence, Gamma");
            verticalAxis.setRange(new Range(0, 1.2));
            verticalAxis.setTickUnit(new NumberTickUnit(0.1));
        } else { // EventCompareSynthetics/StrongMotion
            verticalAxis = new NumberAxis("Displacement (m)");
        }

        Font fontPlain = new Font("Verdana", Font.PLAIN, 14);
        Font fontBold = new Font("Verdana", Font.BOLD, 18);
        verticalAxis.setLabelFont(fontBold);
        verticalAxis.setTickLabelFont(fontPlain);
        horizontalAxis.setLabelFont(fontBold);
        horizontalAxis.setTickLabelFont(fontPlain);

        XYSeriesCollection seriesCollection = new XYSeriesCollection();
        XYDotRenderer renderer = new XYDotRenderer();
        XYPlot xyplot = new XYPlot(seriesCollection, horizontalAxis, verticalAxis, renderer);
        xyplot.setDomainGridlinesVisible(true);
        xyplot.setRangeGridlinesVisible(true);
        xyplot.setRangeGridlinePaint(Color.black);
        xyplot.setDomainGridlinePaint(Color.black);

        // Plot each trace on this panel:
        int iTrace = 0;
        for (Trace trace : panel.getTraces()) {

            XYSeries series = new XYSeries(trace.getName());

            double xdata[] = trace.getxData();
            double ydata[] = trace.getyData();
            for (int k = 0; k < xdata.length; k++) {
                series.add(xdata[k], ydata[k]);
            }

            renderer.setSeriesPaint(iTrace, trace.getColor());
            renderer.setSeriesStroke(iTrace, trace.getStroke());

            seriesCollection.addSeries(series);

            iTrace++;
        }

        // Add Annotations for each trace - This is done in a separate loop
        // so that
        // the upper/lower limits for this panel will be known
        double xmin = horizontalAxis.getRange().getLowerBound();
        double xmax = horizontalAxis.getRange().getUpperBound();
        double ymin = verticalAxis.getRange().getLowerBound();
        double ymax = verticalAxis.getRange().getUpperBound();
        double delX = Math.abs(xmax - xmin);
        double delY = Math.abs(ymax - ymin);

        // Annotation (x,y) in normalized units - where upper-right corner =
        // (1,1)
        double xAnn = 0.97; // Right center coords of the trace name (e.g.,
        // "00-LHZ")
        double yAnn = 0.95;

        double yOff = 0.05; // Vertical distance between different trace
        // legends

        iTrace = 0;
        for (Trace trace : panel.getTraces()) {
            if (!trace.getName().contains("NLNM") && !trace.getName().contains("NHNM")
                    && !trace.getName().contains("ALNM")) {
                // x1 > x2 > x3, e.g.:
                // o-------o 00-LHZ
                // x3 x2 x1

                double scale = .01; // Controls distance between trace label
                // and line segment
                double xL = .04; // Length of trace line segment in legend

                double xAnn2 = xAnn - scale * trace.getName().length();
                double xAnn3 = xAnn - scale * trace.getName().length() - xL;

                double x1 = xAnn * delX + xmin; // Right hand x-coord of
                // text in range units
                double x2 = xAnn2 * delX + xmin; // x-coord of line segment
                // end in range units
                double x3 = xAnn3 * delX + xmin; // x-coord of line segment
                // end in range units

                double y = (yAnn - (iTrace * yOff)) * delY + ymin;

                if (horizontalAxis instanceof LogarithmicAxis) {
                    double logMin = Math.log10(xmin);
                    double logMax = Math.log10(xmax);
                    delX = logMax - logMin;
                    x1 = Math.pow(10, xAnn * delX + logMin);
                    x2 = Math.pow(10, xAnn2 * delX + logMin);
                    x3 = Math.pow(10, xAnn3 * delX + logMin);
                }
                xyplot.addAnnotation(new XYLineAnnotation(x3, y, x2, y, trace.getStroke(), trace.getColor()));
                XYTextAnnotation xyText = new XYTextAnnotation(trace.getName(), x1, y);
                xyText.setFont(new Font("Verdana", Font.BOLD, 18));
                xyText.setTextAnchor(TextAnchor.CENTER_RIGHT);
                xyplot.addAnnotation(xyText);
            }
            iTrace++;
        }

        combinedPlot.add(xyplot, 1);

    } // panel

    final JFreeChart chart = new JFreeChart(combinedPlot);
    chart.setTitle(new TextTitle(plotTitle, new Font("Verdana", Font.BOLD, 18)));
    chart.removeLegend();

    try {
        ChartUtilities.saveChartAsPNG(outputFile, chart, 1400, 1400);
    } catch (IOException e) {
        // System.err.println("Problem occurred creating chart.");
        logger.error("IOException:", e);
    }

}

From source file:asl.util.PlotMaker.java

public void plotCoherence(double per[], double[] gamma, String plotString) {

    final String plotTitle = String.format("%04d%03d.%s.%s-%s", date.get(Calendar.YEAR),
            date.get(Calendar.DAY_OF_YEAR), station, channelX, channelY);
    final String pngName = String.format("%s/%04d%03d.%s.%s-%s.%s.png", outputDir, date.get(Calendar.YEAR),
            date.get(Calendar.DAY_OF_YEAR), station, channelX, channelY, 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("== plotCoherence: request to output plot=[%s] but we are unable to create it "
                + " --> skip plot\n", pngName);
        return;// w  ww .  j av a2s.  c o  m
    }

    final String legend = String.format("%s--%s", channelX, channelY);
    final XYSeries series1 = new XYSeries(legend);

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

    //final XYItemRenderer renderer1 = new StandardXYItemRenderer();
    final XYLineAndShapeRenderer renderer1 = new XYLineAndShapeRenderer();
    Rectangle rectangle = new Rectangle(3, 3);
    renderer1.setSeriesShape(0, rectangle);
    renderer1.setSeriesShapesVisible(0, true);
    renderer1.setSeriesLinesVisible(0, false);

    Paint[] paints = new Paint[] { Color.red, Color.black };
    renderer1.setSeriesPaint(0, paints[0]);

    final NumberAxis rangeAxis1 = new NumberAxis("Coherence, Gamma");
    rangeAxis1.setRange(new Range(0, 1.2));
    rangeAxis1.setTickUnit(new NumberTickUnit(0.1));

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

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

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

    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:org.owasp.benchmark.score.report.ScatterScores.java

private JFreeChart display(String title, int height, int width, List<Report> toolResults) {
    JFrame f = new JFrame(title);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    XYSeriesCollection dataset = new XYSeriesCollection();
    XYSeries series = new XYSeries("Scores");
    for (int i = 0; i < toolResults.size(); i++) {
        Report toolReport = toolResults.get(i);
        OverallResults overallResults = toolReport.getOverallResults();
        series.add(overallResults.getFalsePositiveRate() * 100, overallResults.getTruePositiveRate() * 100);
    }//from www  . ja v a 2s  .  c om
    dataset.addSeries(series);

    chart = ChartFactory.createScatterPlot(title, "False Positive Rate", "True Positive Rate", dataset,
            PlotOrientation.VERTICAL, true, true, false);
    String fontName = "Arial";
    DecimalFormat pctFormat = new DecimalFormat("0'%'");

    theme = (StandardChartTheme) org.jfree.chart.StandardChartTheme.createJFreeTheme();
    theme.setExtraLargeFont(new Font(fontName, Font.PLAIN, 24)); // title
    theme.setLargeFont(new Font(fontName, Font.PLAIN, 20)); // axis-title
    theme.setRegularFont(new Font(fontName, Font.PLAIN, 16));
    theme.setSmallFont(new Font(fontName, Font.PLAIN, 12));
    theme.setRangeGridlinePaint(Color.decode("#C0C0C0"));
    theme.setPlotBackgroundPaint(Color.white);
    theme.setChartBackgroundPaint(Color.white);
    theme.setGridBandPaint(Color.red);
    theme.setAxisOffset(new RectangleInsets(0, 0, 0, 0));
    theme.setBarPainter(new StandardBarPainter());
    theme.setAxisLabelPaint(Color.decode("#666666"));
    theme.apply(chart);

    XYPlot xyplot = chart.getXYPlot();
    NumberAxis rangeAxis = (NumberAxis) xyplot.getRangeAxis();
    NumberAxis domainAxis = (NumberAxis) xyplot.getDomainAxis();

    xyplot.setOutlineVisible(true);

    rangeAxis.setRange(-5, 109.99);
    rangeAxis.setNumberFormatOverride(pctFormat);
    rangeAxis.setTickLabelPaint(Color.decode("#666666"));
    rangeAxis.setMinorTickCount(5);
    rangeAxis.setTickUnit(new NumberTickUnit(10));
    rangeAxis.setAxisLineVisible(true);
    rangeAxis.setMinorTickMarksVisible(true);
    rangeAxis.setTickMarksVisible(true);
    rangeAxis.setLowerMargin(10);
    rangeAxis.setUpperMargin(10);
    xyplot.setRangeGridlineStroke(new BasicStroke());
    xyplot.setRangeGridlinePaint(Color.lightGray);
    xyplot.setRangeMinorGridlinePaint(Color.decode("#DDDDDD"));
    xyplot.setRangeMinorGridlinesVisible(true);

    domainAxis.setRange(-5, 105);
    domainAxis.setNumberFormatOverride(pctFormat);
    domainAxis.setTickLabelPaint(Color.decode("#666666"));
    domainAxis.setMinorTickCount(5);
    domainAxis.setTickUnit(new NumberTickUnit(10));
    domainAxis.setAxisLineVisible(true);
    domainAxis.setTickMarksVisible(true);
    domainAxis.setMinorTickMarksVisible(true);
    domainAxis.setLowerMargin(10);
    domainAxis.setUpperMargin(10);
    xyplot.setDomainGridlineStroke(new BasicStroke());
    xyplot.setDomainGridlinePaint(Color.lightGray);
    xyplot.setDomainMinorGridlinePaint(Color.decode("#DDDDDD"));
    xyplot.setDomainMinorGridlinesVisible(true);

    chart.setTextAntiAlias(true);
    chart.setAntiAlias(true);
    chart.removeLegend();
    chart.setPadding(new RectangleInsets(20, 20, 20, 20));
    xyplot.getRenderer().setSeriesPaint(0, Color.decode("#4572a7"));

    //        // setup item labels
    //        XYItemRenderer renderer = xyplot.getRenderer();
    //        Shape circle = new Ellipse2D.Float(-2.0f, -2.0f, 7.0f, 7.0f);
    //        for ( int i = 0; i < dataset.getSeriesCount(); i++ ) {
    //            renderer.setSeriesShape(i, circle);
    //            renderer.setSeriesPaint(i, Color.blue);
    //            String label = ""+((String)dataset.getSeries(i).getKey());
    //            int idx = label.indexOf( ':');
    //            label = label.substring( 0, idx );
    //            StandardXYItemLabelGenerator generator = new StandardXYItemLabelGenerator(label); 
    //            renderer.setSeriesItemLabelGenerator(i, generator); 
    //            renderer.setSeriesItemLabelsVisible(i, true);
    //            ItemLabelPosition position = new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER );
    //            renderer.setSeriesPositiveItemLabelPosition(i, position);
    //        }

    makeDataLabels(toolResults, xyplot);
    makeLegend(toolResults, 57, 48, dataset, xyplot);

    Stroke dashed = new BasicStroke(1, BasicStroke.CAP_BUTT, BasicStroke.JOIN_BEVEL, 0, new float[] { 6, 3 },
            0);
    for (XYDataItem item : (List<XYDataItem>) series.getItems()) {
        double x = item.getX().doubleValue();
        double y = item.getY().doubleValue();
        double z = (x + y) / 2;
        XYLineAnnotation score = new XYLineAnnotation(x, y, z, z, dashed, Color.blue);
        xyplot.addAnnotation(score);
    }

    //        // put legend inside plot
    //        LegendTitle lt = new LegendTitle(xyplot);
    //        lt.setItemFont(theme.getSmallFont());
    //        lt.setPosition(RectangleEdge.RIGHT);
    //        lt.setItemFont(theme.getSmallFont());
    //        XYTitleAnnotation ta = new XYTitleAnnotation(.7, .55, lt, RectangleAnchor.TOP_LEFT);
    //        ta.setMaxWidth(0.48);
    //        xyplot.addAnnotation(ta);

    // draw guessing line
    XYLineAnnotation guessing = new XYLineAnnotation(-5, -5, 105, 105, dashed, Color.red);
    xyplot.addAnnotation(guessing);

    XYPointerAnnotation worse = makePointer(75, 5, "Worse than guessing", TextAnchor.TOP_CENTER, 90);
    xyplot.addAnnotation(worse);

    XYPointerAnnotation better = makePointer(25, 100, "Better than guessing", TextAnchor.BOTTOM_CENTER, 270);
    xyplot.addAnnotation(better);

    XYTextAnnotation stroketext = new XYTextAnnotation("                     Random Guess", 88, 107);
    stroketext.setTextAnchor(TextAnchor.CENTER_RIGHT);
    stroketext.setBackgroundPaint(Color.white);
    stroketext.setPaint(Color.red);
    stroketext.setFont(theme.getRegularFont());
    xyplot.addAnnotation(stroketext);

    XYLineAnnotation strokekey = new XYLineAnnotation(58, 107, 68, 107, dashed, Color.red);
    xyplot.setBackgroundPaint(Color.white);
    xyplot.addAnnotation(strokekey);

    ChartPanel cp = new ChartPanel(chart, height, width, 400, 400, 1200, 1200, false, false, false, false,
            false, false);
    f.add(cp);
    f.pack();
    f.setLocationRelativeTo(null);
    //      f.setVisible(true);
    return chart;
}

From source file:asl.util.PlotMaker.java

public void plotSpecAmp(double freq[], double[] amp, double[] phase, 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("== plotSpecAmp: request to output plot=[%s] but we are unable to create it "
                + " --> skip plot\n", pngName);
        return;/*from w  w  w .jav a2 s  . c o m*/
    }

    final XYSeries series1 = new XYSeries("Amplitude");
    final XYSeries series2 = new XYSeries("Phase");

    double maxdB = 0.;
    for (int k = 0; k < freq.length; k++) {
        double dB = 20. * Math.log10(amp[k]);
        series1.add(freq[k], dB);
        series2.add(freq[k], phase[k]);
        if (dB > maxdB) {
            maxdB = dB;
        }
    }

    //final XYItemRenderer renderer = new StandardXYItemRenderer();
    final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    Rectangle rectangle = new Rectangle(3, 3);
    renderer.setSeriesShape(0, rectangle);
    //renderer.setSeriesShapesVisible(0, true);
    renderer.setSeriesShapesVisible(0, false);
    renderer.setSeriesLinesVisible(0, true);

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

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

    final XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer();
    renderer2.setSeriesPaint(0, paints[1]);
    renderer2.setSeriesShapesVisible(0, false);
    renderer2.setSeriesLinesVisible(0, true);

    // Stroke is part of Java Swing ...
    //renderer2.setBaseStroke( new Stroke( ... ) );

    double ymax;
    if (maxdB < 10) {
        ymax = 10.;
    } else {
        ymax = maxdB + 2;
        ;
    }

    final NumberAxis verticalAxis = new NumberAxis("Spec Amp (dB)");
    verticalAxis.setRange(new Range(-40, ymax));
    verticalAxis.setTickUnit(new NumberTickUnit(5));

    //final LogarithmicAxis verticalAxis = new LogarithmicAxis("Amplitude Response");
    //verticalAxis.setRange( new Range(0.01 , 10) );

    final LogarithmicAxis horizontalAxis = new LogarithmicAxis("Frequency (Hz)");
    //horizontalAxis.setRange( new Range(0.0001 , 100.5) );
    horizontalAxis.setRange(new Range(0.00009, 110));

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

    final XYPlot xyplot = new XYPlot((XYDataset) seriesCollection, null, verticalAxis, renderer);
    //final XYPlot xyplot = new XYPlot((XYDataset)seriesCollection, horizontalAxis, verticalAxis, renderer);

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

    final NumberAxis phaseAxis = new NumberAxis("Phase (Deg)");
    phaseAxis.setRange(new Range(-180, 180));
    phaseAxis.setTickUnit(new NumberTickUnit(30));
    final XYSeriesCollection seriesCollection2 = new XYSeriesCollection();
    seriesCollection2.addSeries(series2);
    final XYPlot xyplot2 = new XYPlot((XYDataset) seriesCollection2, null, phaseAxis, renderer2);

    //CombinedXYPlot combinedPlot = new CombinedXYPlot( horizontalAxis, CombinedXYPlot.VERTICAL );
    CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(horizontalAxis);
    combinedPlot.add(xyplot, 1);
    combinedPlot.add(xyplot2, 1);
    combinedPlot.setGap(15.);

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

    // Here we need to see if test dir exists and create it if necessary ...
    try {
        //ChartUtilities.saveChartAsJPEG(new File("chart.jpg"), chart, 500, 300);
        //ChartUtilities.saveChartAsPNG(outputFile, chart, 500, 300);
        ChartUtilities.saveChartAsPNG(outputFile, chart, 1000, 800);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");

    }
}

From source file:asl.util.PlotMaker.java

public void plotSpecAmp2(double freq[], double[] amp1, double[] phase1, double[] amp2, double[] phase2,
        String plotTitle, String pngName) {

    /**/*from   ww w  .j  av  a 2 s. c  o m*/
            final String plotTitle = String.format("%04d%03d.%s.%s %s", date.get(Calendar.YEAR), date.get(Calendar.DAY_OF_YEAR)
                                        ,station, channel, plotString);
            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("== plotSpecAmp: request to output plot=[%s] but we are unable to create it "
                + " --> skip plot\n", pngName);
        return;
    }
    // Plot x-axis (frequency) range
    final double XMIN = .00009;
    final double XMAX = freq[freq.length - 1];

    System.out.format("== plotSpecAmp2: nfreq=%d npts=%d pngName=%s\n", freq.length, amp2.length, pngName);

    final XYSeries series1 = new XYSeries("Amp_PZ");
    final XYSeries series1b = new XYSeries("Amp_Cal");

    final XYSeries series2 = new XYSeries("Phase_PZ");
    final XYSeries series2b = new XYSeries("Phase_Cal");

    double maxdB = 0.;
    for (int k = 0; k < freq.length; k++) {
        double dB = amp1[k];
        //double dB = 20. * Math.log10( amp1[k] );
        //series1.add( freq[k], dB );
        //series1.add( freq[k], 20. * Math.log10( amp1[k] ) );
        //series1b.add(freq[k], 20. * Math.log10( amp2[k] ));
        series1.add(freq[k], amp1[k]);
        series1b.add(freq[k], amp2[k]);
        series2.add(freq[k], phase1[k]);
        series2b.add(freq[k], phase2[k]);
        if (dB > maxdB) {
            maxdB = dB;
        }
    }

    //final XYItemRenderer renderer = new StandardXYItemRenderer();
    final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
    Rectangle rectangle = new Rectangle(3, 3);
    renderer.setSeriesShape(0, rectangle);
    //renderer.setSeriesShapesVisible(0, true);
    renderer.setSeriesShapesVisible(0, false);
    renderer.setSeriesLinesVisible(0, true);

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

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

    final XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer();
    renderer2.setSeriesPaint(0, paints[1]);
    renderer2.setSeriesShapesVisible(0, false);
    renderer2.setSeriesLinesVisible(0, true);

    // Stroke is part of Java Swing ...
    //renderer2.setBaseStroke( new Stroke( ... ) );

    double ymax;
    if (maxdB < 10) {
        ymax = 10.;
    } else {
        ymax = maxdB + 2;
        ;
    }

    final NumberAxis verticalAxis = new NumberAxis("Spec Amp (dB)");
    verticalAxis.setRange(new Range(-40, ymax));
    verticalAxis.setTickUnit(new NumberTickUnit(5));

    //final LogarithmicAxis verticalAxis = new LogarithmicAxis("Amplitude Response");
    //verticalAxis.setRange( new Range(0.01 , 10) );

    final LogarithmicAxis horizontalAxis = new LogarithmicAxis("Frequency (Hz)");
    //horizontalAxis.setRange( new Range(0.0001 , 100.5) );
    //horizontalAxis.setRange( new Range(0.00009 , 110) );
    horizontalAxis.setRange(new Range(XMIN, XMAX));

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

    final XYPlot xyplot = new XYPlot((XYDataset) seriesCollection, null, verticalAxis, renderer);
    //final XYPlot xyplot = new XYPlot((XYDataset)seriesCollection, horizontalAxis, verticalAxis, renderer);

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

    final NumberAxis phaseAxis = new NumberAxis("Phase (Deg)");
    phaseAxis.setRange(new Range(-180, 180));
    phaseAxis.setTickUnit(new NumberTickUnit(30));
    final XYSeriesCollection seriesCollection2 = new XYSeriesCollection();
    seriesCollection2.addSeries(series2);
    seriesCollection2.addSeries(series2b);
    final XYPlot xyplot2 = new XYPlot((XYDataset) seriesCollection2, null, phaseAxis, renderer2);

    //CombinedXYPlot combinedPlot = new CombinedXYPlot( horizontalAxis, CombinedXYPlot.VERTICAL );
    CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(horizontalAxis);
    combinedPlot.add(xyplot, 1);
    combinedPlot.add(xyplot2, 1);
    combinedPlot.setGap(15.);

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

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

    }
}

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

/**
 * Generates a chart in PNG format./*from w ww .j  a va2  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);
    }
}

From source file:view.Dashboard.java

public void updateChart() {
    if (cc.getConnectionStatus()) {
        try {//from w w w .j a  v  a  2 s  . c  o  m
            double data = cc.readData();
            if (counter == 1000) {
                voltageSeries.remove(0);
                setPointSeries.remove(0);
            } else if (counter < 1000) {
                counter++;
            }
            voltageSeries.add(currentTime * 50, data);
            setPointSeries.add(currentTime * 50, setPoint);
            xyPlot = (XYPlot) voltageLineChart.getPlot();
            xyPlot.setDomainCrosshairVisible(true);
            xyPlot.setRangeCrosshairVisible(true);
            NumberAxis domain = (NumberAxis) xyPlot.getDomainAxis();
            domain.setRange(currentTime * 50 - tickpoint * 10, currentTime * 50);
            System.out.println(voltageSeries.getItemCount());
            domain.setTickUnit(new NumberTickUnit(tickpoint));
            currentTime++;
            NumberAxis range = (NumberAxis) xyPlot.getRangeAxis();
            switch (setRangeY) {
            case 1:
                range.setRange(0, 5);
                range.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
                break;
            case 2:
                range.setRange(0, 10);
                range.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
                break;
            case 3:
                range.setRange(0, 15);
                range.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
                break;
            default:
                range.setAutoRange(true);
                range.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
                break;
            }
        } catch (SerialPortTimeoutException ex) {
            timer.stop();
            cc.setConnectionStatus(false);
            cc.setReadStatus(false);
        }
    } else {
        timer.stop();
    }
}

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   w ww .j a  va2 s  . c o m*/
                "== 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:org.pentaho.plugin.jfreereport.reportcharts.XYAreaLineChartExpression.java

protected void configureChart(final JFreeChart chart) {
    super.configureChart(chart);

    final XYPlot plot = chart.getXYPlot();

    if (isSharedRangeAxis() == false) {
        final ValueAxis linesAxis = plot.getRangeAxis(1);
        if (linesAxis instanceof NumberAxis) {
            final NumberAxis numberAxis = (NumberAxis) linesAxis;
            numberAxis.setAutoRangeIncludesZero(isLineAxisIncludesZero());
            numberAxis.setAutoRangeStickyZero(isLineAxisStickyZero());

            if (getLinePeriodCount() > 0) {
                if (getLineTicksLabelFormat() != null) {
                    final FastDecimalFormat formatter = new FastDecimalFormat(getLineTicksLabelFormat(),
                            getResourceBundleFactory().getLocale());
                    numberAxis.setTickUnit(new FastNumberTickUnit(getLinePeriodCount(), formatter));
                } else {
                    numberAxis.setTickUnit(new FastNumberTickUnit(getLinePeriodCount()));
                }//from w  w w  . j  av  a  2  s  .  c  o  m
            } else {
                if (getLineTicksLabelFormat() != null) {
                    final DecimalFormat formatter = new DecimalFormat(getLineTicksLabelFormat(),
                            new DecimalFormatSymbols(getResourceBundleFactory().getLocale()));
                    numberAxis.setNumberFormatOverride(formatter);
                }
            }
        } else if (linesAxis instanceof DateAxis) {
            final DateAxis numberAxis = (DateAxis) linesAxis;

            if (getLinePeriodCount() > 0 && getLineTimePeriod() != null) {
                if (getLineTicksLabelFormat() != null) {
                    final SimpleDateFormat formatter = new SimpleDateFormat(getLineTicksLabelFormat(),
                            new DateFormatSymbols(getResourceBundleFactory().getLocale()));
                    numberAxis.setTickUnit(new DateTickUnit(getDateUnitAsInt(getLineTimePeriod()),
                            (int) getLinePeriodCount(), formatter));
                } else {
                    numberAxis.setTickUnit(new DateTickUnit(getDateUnitAsInt(getLineTimePeriod()),
                            (int) getLinePeriodCount()));
                }
            } else if (getRangeTickFormatString() != null) {
                final SimpleDateFormat formatter = new SimpleDateFormat(getRangeTickFormatString(),
                        new DateFormatSymbols(getResourceBundleFactory().getLocale()));
                numberAxis.setDateFormatOverride(formatter);
            }
        }

        if (linesAxis != null) {
            final Font labelFont = Font.decode(getLabelFont());
            linesAxis.setLabelFont(labelFont);
            linesAxis.setTickLabelFont(labelFont);

            if (getLineTitleFont() != null) {
                linesAxis.setLabelFont(getLineTitleFont());
            }
            if (getLineTickFont() != null) {
                linesAxis.setTickLabelFont(getLineTickFont());
            }
            final int level = getRuntime().getProcessingContext().getCompatibilityLevel();
            if (ClassicEngineBoot.isEnforceCompatibilityFor(level, 3, 8)) {
                final double lineRangeMinimumVal = lineRangeMinimum == null ? 0 : lineRangeMinimum;
                final double lineRangeMaximumVal = lineRangeMaximum == null ? 0 : lineRangeMaximum;
                if (lineRangeMinimum != null) {
                    linesAxis.setLowerBound(getLineRangeMinimum());
                }
                if (lineRangeMaximum != null) {
                    linesAxis.setUpperBound(getRangeMaximum());
                }
                if (lineRangeMinimumVal == 0 && lineRangeMaximumVal == 1) {
                    linesAxis.setLowerBound(0);
                    linesAxis.setUpperBound(1);
                    linesAxis.setAutoRange(true);
                }
            } else {
                if (lineRangeMinimum != null) {
                    linesAxis.setLowerBound(lineRangeMinimum);
                }
                if (lineRangeMaximum != null) {
                    linesAxis.setUpperBound(lineRangeMaximum);
                }
                linesAxis.setAutoRange(isLineAxisAutoRange());
            }
        }
    }

    final XYLineAndShapeRenderer linesRenderer = (XYLineAndShapeRenderer) plot.getRenderer(1);
    if (linesRenderer != null) {
        //set stroke with line width
        linesRenderer.setStroke(translateLineStyle(getLineWidth(), getLineStyle()));
        //hide shapes on line
        linesRenderer.setShapesVisible(isMarkersVisible());
        linesRenderer.setBaseShapesFilled(isMarkersVisible());

        //set colors for each line
        for (int i = 0; i < lineSeriesColor.size(); i++) {
            final String s = (String) lineSeriesColor.get(i);
            linesRenderer.setSeriesPaint(i, parseColorFromString(s));
        }
    }
}