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

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

Introduction

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

Prototype

public NumberAxis(String label) 

Source Link

Document

Constructs a number axis, using default values where necessary.

Usage

From source file:edu.gmu.cs.sim.util.media.chart.BoxPlotGenerator.java

protected void buildChart() {
    DefaultBoxAndWhiskerCategoryDataset dataset = new DefaultBoxAndWhiskerCategoryDataset();

    // we build the chart manually rather than using ChartFactory
    // because we need to customize the getDataRange method below

    CategoryAxis categoryAxis = new CategoryAxis("");
    NumberAxis valueAxis = new NumberAxis("Untitled Y Axis");
    valueAxis.setAutoRangeIncludesZero(false);
    BoxAndWhiskerRenderer renderer = new BoxAndWhiskerRenderer();
    renderer.setBaseToolTipGenerator(new BoxAndWhiskerToolTipGenerator());
    CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, valueAxis, renderer) {
        // Customizing this method in order to provide a bit of
        // vertical buffer.  Otherwise the bar chart box gets drawn
        // slightly off-chart, which looks really bad.

        public Range getDataRange(ValueAxis axis) {
            Range range = super.getDataRange(axis);
            if (range == null) {
                return null;
            }/*from   w  w  w .j  av a  2  s . c om*/
            final double EXTRA_PERCENTAGE = 0.02;
            return Range.expand(range, EXTRA_PERCENTAGE, EXTRA_PERCENTAGE);
        }
    };

    chart = new JFreeChart("Untitled Chart", JFreeChart.DEFAULT_TITLE_FONT, plot, false);
    ChartFactory.getChartTheme().apply(chart);

    chart.setAntiAlias(true);
    chartPanel = buildChartPanel(chart);
    setChartPanel(chartPanel);

    // this must come last because the chart must exist for us to set its dataset
    setSeriesDataset(dataset);
}

From source file:org.jfree.chart.demo.MultiShapesXYDemo.java

/**
 * A demonstration application showing a series with different shape attributes per item.
 *
 * @param title  the frame title.//  w  w w.  j ava 2s. co  m
 */
public MultiShapesXYDemo(final String title) {

    super(title);

    System.out.println("About to get images...");
    final URL url1 = getClass().getClassLoader().getResource("org/jfree/chart/demo/redball.png");
    final URL url2 = getClass().getClassLoader().getResource("org/jfree/chart/demo/arrow.png");
    if (url1 != null && url2 != null) {
        this.ballImage = new javax.swing.ImageIcon(url1).getImage();
        this.arrowImage = new javax.swing.ImageIcon(url2).getImage();
        final MediaTracker tracker = new MediaTracker(this);
        tracker.addImage(this.ballImage, 0);
        tracker.addImage(this.arrowImage, 1);
        try {
            tracker.waitForID(0);
            tracker.waitForID(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Images loaded");
    } else {
        System.err.println("Can't find images");
    }
    System.out.println("Images done.");
    this.series = new XYSeries("Some Data");
    for (int i = 0; i < NUMBER_OF_POINTS; i++) {
        final double x = INCREMENT * i;
        final double y = Math.sin(x);
        this.series.add(x, y);
    }
    final XYSeriesCollection data = new XYSeriesCollection(this.series);
    final NumberAxis domainAxis = new NumberAxis("x");
    final NumberAxis rangeAxis = new NumberAxis("sin(x)");
    final DemoRenderer renderer = new DemoRenderer();
    final Plot plot = new XYPlot(data, domainAxis, rangeAxis, renderer);
    final JFreeChart chart = new JFreeChart(plot);
    final ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(600, 380));
    setContentPane(chartPanel);

}

From source file:org.n52.oxf.render.sos.ScatterPlotChartRenderer.java

/**
 * //  www .ja  v a  2s  .  c  om
 * @param dataset
 * @param width
 * @param height
 * @return
 */
private JFreeChart drawChart(List<ObservedValueTuple> tupleList) {

    float[][] data = new float[2][tupleList.size()];
    for (int i = 0; i < tupleList.size(); i++) {
        data[0][i] = ((Double) tupleList.get(i).getValue(0)).floatValue();
        data[1][i] = ((Double) tupleList.get(i).getValue(1)).floatValue();
    }

    String xAxisTitle = observedPropertyX.split(":")[observedPropertyX.split(":").length - 1];
    String yAxisTitle = observedPropertyY.split(":")[observedPropertyY.split(":").length - 1];

    final NumberAxis domainAxis = new NumberAxis(yAxisTitle);
    domainAxis.setAutoRangeIncludesZero(false);
    final NumberAxis rangeAxis = new NumberAxis(xAxisTitle);
    rangeAxis.setAutoRangeIncludesZero(false);

    MyScatterPlot plot = new MyScatterPlot(data, domainAxis, rangeAxis);

    return new JFreeChart(plot);
}

From source file:org.pentaho.plugin.jfreereport.reportcharts.XYAreaChartExpression.java

/**
 * Creates a stacked XY area plot.  The chart object returned by this method uses an {@link
 * org.jfree.chart.plot.XYPlot} instance as the plot, with a {@link org.jfree.chart.axis.NumberAxis} for the domain
 * axis, a {@link org.jfree.chart.axis.NumberAxis} as the range axis, and a {@link
 * org.jfree.chart.renderer.xy.StackedXYAreaRenderer2} as the renderer.
 *
 * @param title       the chart title (<code>null</code> permitted).
 * @param xAxisLabel  a label for the X-axis (<code>null</code> permitted).
 * @param yAxisLabel  a label for the Y-axis (<code>null</code> permitted).
 * @param dataset     the dataset for the chart (<code>null</code> permitted).
 * @param orientation the plot orientation (horizontal or vertical) (<code>null</code> NOT permitted).
 * @param legend      a flag specifying whether or not a legend is required.
 * @param tooltips    configure chart to generate tool tips?
 * @param urls        configure chart to generate URLs?
 * @return A stacked XY area chart./* ww w .  j  a  v  a2s . com*/
 */
protected static JFreeChart createStackedXYAreaChart(final String title, final String xAxisLabel,
        final String yAxisLabel, final XYDataset dataset, final PlotOrientation orientation,
        final boolean legend, final boolean tooltips, final boolean urls) {

    if (orientation == null) {
        throw new IllegalArgumentException("Null 'orientation' argument.");
    }
    final NumberAxis xAxis = new NumberAxis(xAxisLabel);
    xAxis.setAutoRangeIncludesZero(false);
    xAxis.setLowerMargin(0.0);
    xAxis.setUpperMargin(0.0);
    final NumberAxis yAxis = new NumberAxis(yAxisLabel);
    XYToolTipGenerator toolTipGenerator = null;
    if (tooltips) {
        toolTipGenerator = new StandardXYToolTipGenerator();
    }

    XYURLGenerator urlGenerator = null;
    if (urls) {
        urlGenerator = new StandardXYURLGenerator();
    }
    final StackedXYAreaRenderer2 renderer = new StackedXYAreaRenderer2(toolTipGenerator, urlGenerator);
    renderer.setOutline(true);
    final XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
    plot.setOrientation(orientation);

    plot.setRangeAxis(yAxis); // forces recalculation of the axis range

    return new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend);
}

From source file:org.jfree.chart.demo.OverlaidCategoryChartDemo.java

/**
 * Creates a new demo.// w w  w .j  av a 2s. co  m
 *
 * @param title  the frame title.
 */
public OverlaidCategoryChartDemo(String title) {

    super(title);
    DefaultIntervalCategoryDataset barData = null;
    double[][] lows = { { -.0315, .0159, .0306, .0453, .0557 } };
    double[][] highs = { { .1931, .1457, .1310, .1163, .1059 } };
    barData = new DefaultIntervalCategoryDataset(lows, highs);

    double[][] vals = { { 0.0808, 0.0808, 0.0808, 0.0808, 0.0808 } };
    CategoryDataset dotData = DatasetUtilities.createCategoryDataset("Series ", "Category ", vals);

    double[][] lineVals = new double[4][5];
    for (int i = 0; i < 4; i++) {
        for (int j = 0; j < 5; j++) {
            lineVals[i][j] = (Math.random() * 0.56) - 0.18;
        }
    }
    CategoryDataset lineData = DatasetUtilities.createCategoryDataset("Series ", "Category ", lineVals);

    String ctitle = "Strategie Sicherheit";
    String xTitle = "Zeitraum (in Jahren)";
    String yTitle = "Performance";
    CategoryAxis xAxis = new CategoryAxis(xTitle);
    xAxis.setLabelFont(titleFont);
    xAxis.setTickLabelFont(labelFont);
    xAxis.setTickMarksVisible(false);
    NumberAxis yAxis = new NumberAxis(yTitle);
    yAxis.setLabelFont(titleFont);
    yAxis.setTickLabelFont(labelFont);
    yAxis.setRange(-0.2, 0.4);
    DecimalFormat formatter = new DecimalFormat("0.##%");
    yAxis.setTickUnit(new NumberTickUnit(0.05, formatter));

    IntervalBarRenderer barRenderer = new IntervalBarRenderer();
    barRenderer.setItemLabelsVisible(Boolean.TRUE);

    CategoryPlot plot = new CategoryPlot(barData, xAxis, yAxis, barRenderer);
    plot.setDatasetRenderingOrder(DatasetRenderingOrder.REVERSE);

    plot.setBackgroundPaint(Color.lightGray);
    plot.setOutlinePaint(Color.black);

    LineAndShapeRenderer dotRenderer = new LineAndShapeRenderer(LineAndShapeRenderer.SHAPES);
    dotRenderer.setItemLabelsVisible(Boolean.TRUE);

    plot.setSecondaryDataset(0, dotData);
    plot.setSecondaryRenderer(0, dotRenderer);

    LineAndShapeRenderer lineRenderer = new LineAndShapeRenderer(LineAndShapeRenderer.SHAPES_AND_LINES);
    plot.setSecondaryDataset(1, lineData);
    plot.setSecondaryRenderer(1, lineRenderer);

    this.chart = new JFreeChart(ctitle, titleFont, plot, false);
    this.chart.setBackgroundPaint(Color.white);

    ChartPanel chartPanel = new ChartPanel(this.chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
    setContentPane(chartPanel);

}

From source file:org.geoserver.monitor.web.ActivityChartBasePanel.java

JFreeChart createTimeSeriesChart(String title, String timeAxisLabel, String valueAxisLabel, XYDataset dataset) {

    ValueAxis timeAxis = new DateAxis(timeAxisLabel);
    timeAxis.setLowerMargin(0.02); // reduce the default margins 
    timeAxis.setUpperMargin(0.02);//  w w w.j a  va2 s  .  co  m
    NumberAxis valueAxis = new NumberAxis(valueAxisLabel);
    valueAxis.setAutoRangeIncludesZero(false); // override default

    XYPlot plot = new XYPlot(dataset, timeAxis, valueAxis, null);

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

    JFreeChart chart = new JFreeChart(plot);

    //TextTitle t = new TextTitle(title);
    //t.setTextAlignment(HorizontalAlignment.LEFT);

    //chart.setTitle(t);
    chart.setBackgroundPaint(Color.WHITE);
    chart.setAntiAlias(true);
    chart.clearSubtitles();

    return chart;
}

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

/**
 *  Add a series to the charts/*from w ww  . ja va2 s .c  om*/
 *
 *
 * @param series   series
 * @param lineState line state
 * @param paramIdx  param index
 * @param renderer  renderer
 * @param rangeVisible range visible
 *
 * @return  the Axis
 */
protected Axis addSeries(XYSeries series, LineState lineState, int paramIdx, XYItemRenderer renderer,
        boolean rangeVisible) {

    if (lineState.getRange() != null) {
        addRange(lineState.getRange().getMin(), lineState.getRange().getMax(),
                "Fixed range from: " + lineState.getName());
    }

    if (numberFormat == null) {
        numberFormat = new DecimalFormat() {
            public StringBuffer format(double number, StringBuffer result, FieldPosition fieldPosition) {

                String s = control.getDisplayConventions().format(number);
                result.append(s);
                return result;
            }
        };

    }

    String name = lineState.getName();
    Unit unit = lineState.unit;
    XYSeriesCollection dataset = new XYSeriesCollection();
    dataset.addSeries(series);

    NumberAxis rangeAxis;
    NumberAxis domainAxis = null;
    String axisLabel = name + ((unit != null) ? " [" + unit + "]" : "");

    if (lineState.getUseLogarithmicRange() && false) {
        rangeAxis = new FixedWidthLogarithmicAxis(axisLabel);
    } else {
        //rangeAxis = new FixedWidthNumberAxis(axisLabel);
        rangeAxis = new NumberAxis(axisLabel);
        ((NumberAxis) rangeAxis).setAutoRangeIncludesZero(lineState.getRangeIncludesZero());
        VerticalProfileInfo vpInfo = (VerticalProfileInfo) profiles.get(0);
        Unit altUnit = vpInfo.getAltitudeUnit();
        if (altUnit != null && paramIdx == 0 && !(altUnit.equals(CommonUnit.meter))) {
            String dlabel = "Altitude " + "[" + altUnit + "]";
            domainAxis = new NumberAxis(dlabel);
            if (altUnit.isConvertible(CommonUnits.HECTOPASCAL))
                domainAxis.setInverted(true);
        }
    }

    //For now lets use the default number formatting for the range
    //        rangeAxis.setNumberFormatOverride(numberFormat);

    rangeAxis.setVisible(rangeVisible);

    ucar.unidata.util.Range r = lineState.getRange();
    if (r != null) {
        rangeAxis.setRange(new org.jfree.data.Range(r.getMin(), r.getMax()));
    }

    if (renderer == null) {
        renderer = getRenderer(lineState);
    }

    Paint c = lineState.getColor(paramIdx);
    rangeAxis.setLabelPaint(Color.black);
    renderer.setSeriesPaint(0, c);
    renderer.setSeriesStroke(0, lineState.getStroke());

    if (!lineState.getAxisVisible()) {
        rangeAxis.setVisible(false);
    }

    AxisLocation side = null;
    ChartHolder chartHolder = getChartHolder(lineState);
    if (rangeAxis.isVisible()) {
        if (lineState.getSide() == LineState.SIDE_UNDEFINED) {
            side = AxisLocation.BOTTOM_OR_RIGHT;
        } else if (lineState.getSide() == LineState.SIDE_LEFT) {
            side = AxisLocation.TOP_OR_LEFT;
        } else {
            side = AxisLocation.BOTTOM_OR_RIGHT;
        }
        chartHolder.lastSide = side;
    }

    synchronized (MUTEX) {
        if (domainAxis == null) {
            if (isConservedSounding)
                chartHolder.add(dataset, renderer, side);
            else
                chartHolder.add(dataset, rangeAxis, renderer, side);

        } else
            chartHolder.add(dataset, rangeAxis, domainAxis, renderer, side);
    }

    return rangeAxis;
}

From source file:com.ewcms.plugin.report.generate.service.chart.ChartGenerationService.java

/**
 * ?//from   w  w w. ja va 2  s  . c om
 *
 * @param title 
 * @param titleFont 
 * @param categoryAxisLabel 
 * @param valueAxisLabel 
 * @param data ??
 * @param orientation ?
 * @param legend 
 * @param tooltips ????
 * @param urls ??URL
 * @param urlGenerator
 *
 * @return ?
 */
public static JFreeChart createBarChart(String title, java.awt.Font titleFont, String categoryAxisLabel,
        String valueAxisLabel, CategoryDataset data, PlotOrientation orientation, boolean legend,
        boolean tooltips, boolean urls, CategoryURLGenerator urlGenerator) {
    CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);
    ValueAxis valueAxis = new NumberAxis(valueAxisLabel);
    BarRenderer renderer = new BarRenderer();

    if (tooltips) {
        //            renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());
        renderer.setBaseToolTipGenerator(new StandardCategoryToolTipGenerator());
    }
    if (urls) {
        //            renderer.setItemURLGenerator(urlGenerator);
        renderer.setBaseItemURLGenerator(urlGenerator);
    }
    CategoryPlot plot = new CategoryPlot(data, categoryAxis, valueAxis, renderer);
    plot.setOrientation(orientation);
    JFreeChart chart = new JFreeChart(title, titleFont, plot, legend);

    return chart;

}

From source file:de.suse.swamp.modules.scheduledjobs.Statistics.java

/**
 * Generating the graphs that show the amount of running finished wfs over the time.
 *//*from  w w w .  ja v a2s . c o m*/
protected void generateWorkflowGraph(String templateName, Date startDate, Date endDate) throws Exception {
    List stats = StatisticStorage.loadStats(templateName, startDate, endDate);
    // only generate if we have stats: 
    if (stats != null && stats.size() > 0) {
        TimeSeriesCollection dataset = new TimeSeriesCollection();
        TimeSeriesCollection avgdataset = new TimeSeriesCollection();
        TimeSeries serie = new TimeSeries("running workflows", Day.class);
        TimeSeries avgserie = new TimeSeries("average age", Day.class);
        for (Iterator datait = stats.iterator(); datait.hasNext();) {
            Dbstatistics statisticItem = (Dbstatistics) datait.next();
            serie.addOrUpdate(new Day(statisticItem.getDate()), statisticItem.getRunningcount());
            avgserie.addOrUpdate(new Day(statisticItem.getDate()), statisticItem.getAvgage() / (3600 * 24));
        }
        dataset.addSeries(serie);
        avgdataset.addSeries(avgserie);

        JFreeChart chart = ChartFactory.createTimeSeriesChart("Running " + templateName + " workflows", "Date",
                "running workflows", dataset, false, false, false);

        // modify chart appearance
        chart.setBackgroundImageAlpha(0.5f);
        XYPlot plot = chart.getXYPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);
        plot.getRangeAxis().setLabelPaint(Color.blue);

        // add the second line: 
        final NumberAxis axis2 = new NumberAxis("Avg. age in days");
        axis2.setLabelPaint(Color.red);
        plot.setRangeAxis(1, axis2);
        plot.setDataset(1, avgdataset);
        plot.mapDatasetToRangeAxis(1, 1);

        final XYLineAndShapeRenderer renderer2 = new XYLineAndShapeRenderer();
        renderer2.setDrawOutlines(false);
        renderer2.setDrawSeriesLineAsPath(true);
        renderer2.setBaseShapesVisible(false);
        plot.setRenderer(1, renderer2);

        File image = new File(statPath + fs + templateName + ".png");
        if (image.exists())
            image.delete();
        try {
            ChartUtilities.saveChartAsPNG(image, chart, 750, 200);
        } catch (Exception e) {
            Logger.ERROR("Error generating graph for " + templateName + ", e: " + e.getMessage());
            e.printStackTrace();
            throw e;
        }
    }
}

From source file:edu.fullerton.viewerplugin.TsPlot.java

@Override
public ArrayList<Integer> makePlot(ArrayList<ChanDataBuffer> dbufs, boolean compact) throws WebUtilException {
    int imageId;//from   ww w. j a  v  a2s  . c om
    try {
        if (parameterMap.containsKey("ts_newplt")) {
            imageId = makeAddPlotFiles(dbufs, compact);
        } else {
            String gtitle = getTitle(dbufs, compact);

            XYSeriesCollection xyds = new XYSeriesCollection();
            TimeSeriesCollection mtds = new TimeSeriesCollection();

            compact = dbufs.size() > 2 ? false : compact;
            for (ChanDataBuffer dbuf : dbufs) {
                if (timeAxis.equalsIgnoreCase("utc")) {
                    addTimeSeries(dbuf, compact, mtds);
                } else {
                    addXySeries(dbuf, compact, xyds);
                }
            }
            Double minx, miny, maxx, maxy;
            Double[] rng = new Double[4];

            if (timeAxis.equalsIgnoreCase("utc")) {
                PluginSupport.getRangeLimits(mtds, rng);
            } else {
                PluginSupport.getRangeLimits(xyds, rng, 0);
            }
            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)", "Amplitude (Counts)", ds, true,
                        true, false);
            } else {
                chart = ChartFactory.createXYLineChart(gtitle, xAxisLabel, "Amplitude (Counts)", ds,
                        PlotOrientation.VERTICAL, true, false, false);
            }

            XYPlot plot = (XYPlot) chart.getPlot();
            NumberAxis rangeAxis = new NumberAxis("Amplitude (Counts)");
            ScaledAxisNumberFormat sanf = new ScaledAxisNumberFormat();
            sanf.setExp(exp);
            if (maxy != 0 && Math.abs(maxy - miny) <= Math.abs(maxy) * 1e-25) {
                // this garbage is to get jFreeChart to 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);
                NumberTickUnit unit = new NumberTickUnit((scaledMax - scaledMin) / 10.);
                rangeAxis.setTickUnit(unit);
                rangeAxis.setAutoRange(false);
            }
            //                else
            //                {
            //                    sanf.setMinMax(miny, maxy);
            //                    rangeAxis.setRange(miny, maxy);
            //                    NumberTickUnit unit = new NumberTickUnit((maxy  - miny)/6.);
            //                    rangeAxis.setTickUnit(unit);
            //                    rangeAxis.setAutoRange(false);
            //                }
            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);
            }
            plot.setBackgroundPaint(Color.WHITE);
            // add 
            plot.setDomainGridlinesVisible(true);
            plot.setDomainGridlinePaint(Color.BLACK);
            plot.setRangeGridlinesVisible(true);
            plot.setRangeGridlinePaint(Color.BLACK);

            r.setBaseFillPaint(Color.WHITE);
            if (compact) {
                chart.removeLegend();
            }

            chart.setBackgroundPaint(Color.WHITE);

            cpnl = new ChartPanel(chart);
            imageId = saveImageAsPNG(cpnl);
        }
    } catch (LdvTableException | NoSuchAlgorithmException | SQLException | IOException ex) {
        throw new WebUtilException("Making time series plot: ", ex);
    }
    ArrayList<Integer> ret = new ArrayList<Integer>();
    ret.add(imageId);
    return ret;
}