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

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

Introduction

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

Prototype

public DateAxis(String label) 

Source Link

Document

Creates a date axis with the specified label.

Usage

From source file:org.hxzon.demo.jfreechart.OtherDatasetDemo.java

private static JFreeChart createHighLowChart(OHLCDataset dataset) {
    ValueAxis timeAxis = new DateAxis(xAxisLabel);
    NumberAxis valueAxis = new NumberAxis(yAxisLabel);
    HighLowRenderer renderer = new HighLowRenderer();
    renderer.setBaseToolTipGenerator(new HighLowItemLabelGenerator());
    XYPlot plot = new XYPlot(dataset, timeAxis, valueAxis, renderer);
    JFreeChart chart = new JFreeChart("HighLow Chart Demo", JFreeChart.DEFAULT_TITLE_FONT, plot, legend);
    chart.setBackgroundPaint(Color.white);

    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);

    return chart;
}

From source file:weka.classifiers.timeseries.eval.graph.JFreeChartDriver.java

protected JFreeChart getFutureForecastChart(TSForecaster forecaster, List<List<NumericPrediction>> preds,
        List<String> targetNames, Instances history) {

    if (forecaster instanceof TSLagUser && history != null) {
        TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker();
        if (lagMaker.getAdjustForTrends() && !lagMaker.isUsingAnArtificialTimeIndex()) {

            // fill in any missing time stamps only
            history = new Instances(history);
            history = weka.classifiers.timeseries.core.Utils.replaceMissing(history, null,
                    lagMaker.getTimeStampField(), true, lagMaker.getPeriodicity(), lagMaker.getSkipEntries());
        }/*from w  ww. ja va  2s . c  o  m*/
    }

    // set up a collection of series
    XYIntervalSeriesCollection xyDataset = new XYIntervalSeriesCollection();

    if (history != null) {
        // add actual historical data values
        for (String targetName : targetNames) {
            XYIntervalSeries targetSeries = new XYIntervalSeries(targetName, false, false);
            xyDataset.addSeries(targetSeries);
        }
    }

    // add predicted series
    for (String targetName : targetNames) {
        XYIntervalSeries targetSeries = new XYIntervalSeries(targetName + "-predicted", false, false);
        xyDataset.addSeries(targetSeries);
    }

    ValueAxis timeAxis = null;
    NumberAxis valueAxis = new NumberAxis("");
    valueAxis.setAutoRangeIncludesZero(false);
    int timeIndex = -1;
    boolean timeAxisIsDate = false;
    double artificialTimeStart = 0;
    double lastRealTimeValue = Utils.missingValue();
    if (forecaster instanceof TSLagUser && history != null) {
        TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker();
        if (!lagMaker.isUsingAnArtificialTimeIndex() && lagMaker.getAdjustForTrends()) {
            String timeName = lagMaker.getTimeStampField();
            if (history.attribute(timeName).isDate()) {
                timeAxis = new DateAxis("");
                timeAxisIsDate = true;
                timeIndex = history.attribute(timeName).index();
            }
        } else {
            try {
                artificialTimeStart = (history != null) ? 1 : lagMaker.getArtificialTimeStartValue() + 1;
            } catch (Exception ex) {
            }
        }
    }

    if (timeAxis == null) {
        timeAxis = new NumberAxis("");
        ((NumberAxis) timeAxis).setAutoRangeIncludesZero(false);
    }

    boolean hasConfidenceIntervals = false;

    // now populate the series
    if (history != null) {

        // do the actuals first
        for (int i = 0; i < history.numInstances(); i++) {
            Instance current = history.instance(i);

            for (String targetName : targetNames) {
                int dataIndex = history.attribute(targetName.trim()).index();

                if (dataIndex >= 0) {
                    XYIntervalSeries actualSeries = null;
                    int actualIndex = xyDataset.indexOf(targetName);
                    actualSeries = xyDataset.getSeries(actualIndex);
                    double x = Utils.missingValue();

                    if (timeAxisIsDate) {
                        x = current.value(timeIndex);
                        if (!Utils.isMissingValue(x)) {
                            lastRealTimeValue = x;
                        }
                    } else {
                        x = artificialTimeStart;
                    }

                    double y = Utils.missingValue();
                    y = current.value(dataIndex);

                    if (!Utils.isMissingValue(x) && !Utils.isMissingValue(y)) {
                        if (actualSeries != null) {
                            actualSeries.add(x, x, x, y, y, y);
                        }
                    }
                }
            }

            if (!timeAxisIsDate) {
                artificialTimeStart++;
            }
        }
    }

    // now do the futures
    List<String> forecasterTargets = AbstractForecaster.stringToList(forecaster.getFieldsToForecast());

    // loop over the steps
    for (int j = 0; j < preds.size(); j++) {
        List<NumericPrediction> predsForStepJ = preds.get(j);

        // advance the real time index (if appropriate)
        if (timeAxisIsDate) {
            lastRealTimeValue = ((TSLagUser) forecaster).getTSLagMaker()
                    .advanceSuppliedTimeValue(lastRealTimeValue);
        }
        for (String targetName : targetNames) {

            // look up this requested target in the list that the forecaster
            // has predicted
            int predIndex = forecasterTargets.indexOf(targetName.trim());
            if (predIndex >= 0) {
                NumericPrediction predsForTargetAtStepJ = predsForStepJ.get(predIndex);
                XYIntervalSeries predSeries = null;
                int datasetIndex = xyDataset.indexOf(targetName + "-predicted");
                predSeries = xyDataset.getSeries(datasetIndex);

                if (predSeries != null) {
                    double y = predsForTargetAtStepJ.predicted();
                    double x = Utils.missingValue();
                    double yHigh = y;
                    double yLow = y;
                    double[][] conf = predsForTargetAtStepJ.predictionIntervals();
                    if (conf.length > 0) {
                        yLow = conf[0][0];
                        yHigh = conf[0][1];
                        hasConfidenceIntervals = true;
                    }

                    if (!timeAxisIsDate) {
                        x = artificialTimeStart;
                    } else {
                        x = lastRealTimeValue;
                    }

                    if (!Utils.isMissingValue(x) && !Utils.isMissingValue(y)) {
                        predSeries.add(x, x, x, y, yLow, yHigh);
                    }
                }
            }
        }

        // advance the artificial time index (if appropriate)
        if (!timeAxisIsDate) {
            artificialTimeStart++;
        }
    }

    String title = "Future forecast for: ";
    for (String s : targetNames) {
        title += s + ",";
    }
    title = title.substring(0, title.lastIndexOf(","));

    /*
     * String algoSpec = forecaster.getAlgorithmName(); title += " (" + algoSpec
     * + ")";
     */

    if (forecaster instanceof WekaForecaster && hasConfidenceIntervals) {
        double confPerc = ((WekaForecaster) forecaster).getConfidenceLevel() * 100.0;
        title += " [" + Utils.doubleToString(confPerc, 0) + "% conf. intervals]";
    }

    XYErrorRenderer renderer = new XYErrorRenderer();

    // renderer.setShapesFilled(true);
    XYPlot plot = new XYPlot(xyDataset, timeAxis, valueAxis, renderer);
    // renderer = (XYErrorRenderer)plot.getRenderer();
    if (history != null) {
        for (String targetName : targetNames) {
            XYIntervalSeries predSeries = null;
            int predIndex = xyDataset.indexOf(targetName + "-predicted");
            predSeries = xyDataset.getSeries(predIndex);

            XYIntervalSeries actualSeries = null;
            int actualIndex = xyDataset.indexOf(targetName);
            actualSeries = xyDataset.getSeries(actualIndex);

            if (actualSeries != null && predSeries != null) {
                // match the color of the actual series
                java.awt.Paint actualPaint = renderer.lookupSeriesPaint(actualIndex);
                renderer.setSeriesPaint(predIndex, actualPaint);

                // now set the line style to dashed
                BasicStroke dashed = new BasicStroke(1.5f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f,
                        new float[] { 5.0f }, 0.0f);

                renderer.setSeriesStroke(predIndex, dashed);
            }
        }
    }

    renderer.setBaseLinesVisible(true);
    renderer.setDrawXError(false);
    renderer.setDrawYError(true);

    JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, true);
    chart.setBackgroundPaint(java.awt.Color.white);
    TextTitle chartTitle = chart.getTitle();
    String fontName = chartTitle.getFont().getFontName();
    java.awt.Font newFont = new java.awt.Font(fontName, java.awt.Font.PLAIN, 12);
    chartTitle.setFont(newFont);

    return chart;
}

From source file:ca.sqlpower.wabit.swingui.chart.ChartSwingUtil.java

/**
 * This is a helper method for creating a line chart. This should only do
 * the chart creation and not setting up the dataset. The calling method
 * should do the logic for the dataset setup.
 * @param c //from ww w.j a v a 2 s .  c  om
 * 
 * @param xyCollection
 *            The dataset to display a chart for.
 * @param chartType
 *            The chart type. This must be a valid chart type that can be
 *            created from an XY dataset. At current only line and scatter
 *            are supported
 * @param legendPosition
 *            The position of the legend.
 * @param chartName
 *            The name of the chart.
 * @param yaxisName
 *            The name of the y axis.
 * @param xaxisName
 *            The name of the x axis.
 * @return A chart of the specified chartType based on the given dataset.
 */
private static JFreeChart createChartFromXYDataset(Chart c, XYDataset xyCollection, ChartType chartType,
        LegendPosition legendPosition, String chartName, String yaxisName, String xaxisName) {
    boolean showLegend = !legendPosition.equals(LegendPosition.NONE);
    JFreeChart chart;
    if (chartType.equals(ChartType.LINE)) {
        chart = ChartFactory.createXYLineChart(chartName, xaxisName, yaxisName, xyCollection,
                PlotOrientation.VERTICAL, showLegend, true, false);
    } else if (chartType.equals(ChartType.SCATTER)) {
        chart = ChartFactory.createScatterPlot(chartName, xaxisName, yaxisName, xyCollection,
                PlotOrientation.VERTICAL, showLegend, true, false);
    } else {
        throw new IllegalArgumentException("Unknown chart type " + chartType + " for an XY dataset.");
    }
    if (chart == null)
        return null;
    XYPlot plot = (XYPlot) chart.getPlot();

    // XXX the following instance check is brittle; there are many ways to represent a time
    // series in JFreeChart. This check uses knowledge of the inner workings of DatasetUtil.
    if (xyCollection instanceof TimePeriodValuesCollection) {
        logger.debug("Switching x-axis to date axis so labels render properly");
        plot.setDomainAxis(new DateAxis(xaxisName));
        // TODO user-settable date format
        // axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));
    }

    if (legendPosition != LegendPosition.NONE) {
        chart.getLegend().setPosition(legendPosition.getRectangleEdge());
    }

    if (!c.isAutoXAxisRange()) {
        XYPlot xyplot = chart.getXYPlot();
        ValueAxis axis = xyplot.getDomainAxis();
        axis.setAutoRange(false);
        axis.setRange(c.getXAxisMinRange(), c.getXAxisMaxRange());
    }
    if (!c.isAutoYAxisRange()) {
        XYPlot xyplot = chart.getXYPlot();
        ValueAxis axis = xyplot.getRangeAxis();
        axis.setAutoRange(false);
        axis.setRange(c.getYAxisMinRange(), c.getYAxisMaxRange());
    }

    return chart;
}

From source file:org.hxzon.demo.jfreechart.OtherDatasetDemo.java

private static JFreeChart createBoxAndWhiskerChart(BoxAndWhiskerXYDataset dataset) {
    ValueAxis timeAxis = new DateAxis(xAxisLabel);
    NumberAxis valueAxis = new NumberAxis(yAxisLabel);
    valueAxis.setAutoRangeIncludesZero(false);

    XYBoxAndWhiskerRenderer renderer = new XYBoxAndWhiskerRenderer(10.0);
    XYPlot plot = new XYPlot(dataset, timeAxis, valueAxis, renderer);
    JFreeChart chart = new JFreeChart("BoxAndWhiskerXY Chart Demo", JFreeChart.DEFAULT_TITLE_FONT, plot,
            legend);/* w  w  w . j  a  va 2s  .  c  om*/
    chart.setBackgroundPaint(Color.white);

    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);

    return chart;
}

From source file:org.hxzon.demo.jfreechart.CategoryDatasetDemo2.java

private static JFreeChart createGanttChart(CategoryDataset dataset) {

    CategoryAxis categoryAxis = new CategoryAxis(categoryAxisLabel);
    DateAxis dateAxis = new DateAxis(valueAxisLabel);

    CategoryItemRenderer renderer = new GanttRenderer();
    if (tooltips) {
        renderer.setBaseToolTipGenerator(
                new IntervalCategoryToolTipGenerator("{3} - {4}", DateFormat.getDateInstance()));
    }/*from   w ww  . ja  v  a 2s  .  c o  m*/
    if (urls) {
        renderer.setBaseItemURLGenerator(new StandardCategoryURLGenerator());
    }

    CategoryPlot plot = new CategoryPlot(dataset, categoryAxis, dateAxis, renderer);
    plot.setOrientation(PlotOrientation.HORIZONTAL);
    JFreeChart chart = new JFreeChart("Gantt Chart Demo 1", JFreeChart.DEFAULT_TITLE_FONT, plot, legend);
    chart.setBackgroundPaint(Color.white);

    GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.blue, 0.0f, 0.0f, new Color(0, 0, 64));
    GradientPaint gp1 = new GradientPaint(0.0f, 0.0f, Color.green, 0.0f, 0.0f, new Color(0, 64, 0));
    GradientPaint gp2 = new GradientPaint(0.0f, 0.0f, Color.red, 0.0f, 0.0f, new Color(64, 0, 0));
    renderer.setSeriesPaint(0, gp0);
    renderer.setSeriesPaint(1, gp1);
    renderer.setSeriesPaint(2, gp2);

    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);

    return chart;

}

From source file:org.hxzon.demo.jfreechart.OtherDatasetDemo.java

private static JFreeChart createWindChart(WindDataset dataset) {
    ValueAxis xAxis = new DateAxis(xAxisLabel);
    ValueAxis yAxis = new NumberAxis("Direction / Force");
    yAxis.setRange(-12.0, 12.0);//from  w  w w.j a  va  2s . c  o  m

    WindItemRenderer renderer = new WindItemRenderer();
    if (tooltips) {
        renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
    }
    if (urls) {
        renderer.setURLGenerator(new StandardXYURLGenerator());
    }
    XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
    JFreeChart chart = new JFreeChart("Wind Chart Demo", JFreeChart.DEFAULT_TITLE_FONT, plot, legend);
    chart.setBackgroundPaint(Color.white);

    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);

    return chart;
}

From source file:com.rapidminer.gui.plotter.charts.Abstract2DChartPlotter.java

@Override
public void updatePlotter() {
    prepareData();/*from  w w  w.jav  a  2  s  .c  o  m*/
    JFreeChart chart;
    if (axis[X_AXIS] >= 0 && axis[Y_AXIS] >= 0) {
        if (nominal) {
            int size = dataSet.getSeriesCount();
            chart = ChartFactory.createScatterPlot(null, // chart title
                    null, // domain axis label
                    null, // range axis label
                    dataSet, // data
                    PlotOrientation.VERTICAL, // orientation
                    colorColumn >= 0 && size < 100 ? true : false, // include legend
                    true, // tooltips
                    false // URLs
            );

            // renderer settings
            try {
                chart.getXYPlot().setRenderer(getItemRenderer(nominal, size, this.minColor, this.maxColor));
            } catch (Exception e) {
                // do nothing
            }

            // legend settings
            LegendTitle legend = chart.getLegend();
            if (legend != null) {
                legend.setPosition(RectangleEdge.TOP);
                legend.setFrame(BlockBorder.NONE);
                legend.setHorizontalAlignment(HorizontalAlignment.LEFT);
                legend.setItemFont(LABEL_FONT);

                BlockContainer wrapper = new BlockContainer(new BorderArrangement());

                LabelBlock title = new LabelBlock(getDataTable().getColumnName(colorColumn),
                        new Font("SansSerif", Font.BOLD, 12));
                title.setPadding(0, 5, 5, 5);
                wrapper.add(title, RectangleEdge.LEFT);

                BlockContainer items = legend.getItemContainer();
                wrapper.add(items, RectangleEdge.RIGHT);

                legend.setWrapper(wrapper);
            }
        } else {

            chart = ChartFactory.createScatterPlot(null, // chart title
                    null, // domain axis label
                    null, // range axis label
                    dataSet, // data
                    PlotOrientation.VERTICAL, // orientation
                    false, // include legend
                    true, // tooltips
                    false // URLs
            );

            // renderer settings
            try {
                chart.getXYPlot().setRenderer(getItemRenderer(nominal, -1, minColor, maxColor));
            } catch (Exception e) {
                // do nothing
            }

            LegendTitle legendTitle = new LegendTitle(chart.getXYPlot().getRenderer()) {

                private static final long serialVersionUID = 1288380309936848376L;

                @Override
                public Object draw(java.awt.Graphics2D g2, java.awt.geom.Rectangle2D area,
                        java.lang.Object params) {
                    if (dataTable.isDate(colorColumn) || dataTable.isTime(colorColumn)
                            || dataTable.isDateTime(colorColumn)) {
                        drawSimpleDateLegend(g2, (int) (area.getCenterX() - 170), (int) (area.getCenterY() + 7),
                                dataTable, colorColumn, minColor, maxColor);
                        return new BlockResult();
                    } else {
                        final String minColorString = Tools.formatNumber(minColor);
                        final String maxColorString = Tools.formatNumber(maxColor);
                        drawSimpleNumericalLegend(g2, (int) (area.getCenterX() - 75),
                                (int) (area.getCenterY() + 7), getDataTable().getColumnName(colorColumn),
                                minColorString, maxColorString);
                        return new BlockResult();
                    }
                }

                @Override
                public void draw(java.awt.Graphics2D g2, java.awt.geom.Rectangle2D area) {
                    draw(g2, area, null);
                }

            };

            BlockContainer wrapper = new BlockContainer(new BorderArrangement());

            LabelBlock title = new LabelBlock(getDataTable().getColumnName(colorColumn),
                    new Font("SansSerif", Font.BOLD, 12));
            title.setPadding(0, 5, 5, 5);
            wrapper.add(title, RectangleEdge.LEFT);

            BlockContainer items = legendTitle.getItemContainer();
            wrapper.add(items, RectangleEdge.RIGHT);

            legendTitle.setWrapper(wrapper);

            chart.addLegend(legendTitle);
        }
    } else {
        chart = ChartFactory.createScatterPlot(null, // chart title
                null, // domain axis label
                null, // range axis label
                dataSet, // data
                PlotOrientation.VERTICAL, // orientation
                false, // include legend
                true, // tooltips
                false // URLs
        );
    }

    // GENERAL CHART SETTINGS

    // set the background colors for the chart...
    chart.setBackgroundPaint(Color.WHITE);
    chart.getPlot().setBackgroundPaint(Color.WHITE);
    chart.setAntiAlias(false);

    // general plot settings
    XYPlot plot = chart.getXYPlot();
    plot.setDomainGridlinePaint(Color.LIGHT_GRAY);
    plot.setRangeGridlinePaint(Color.LIGHT_GRAY);

    // domain axis
    if (axis[X_AXIS] >= 0) {
        if (dataTable.isNominal(axis[X_AXIS])) {
            String[] values = new String[dataTable.getNumberOfValues(axis[X_AXIS])];
            for (int i = 0; i < values.length; i++) {
                values[i] = dataTable.mapIndex(axis[X_AXIS], i);
            }
            plot.setDomainAxis(new SymbolAxis(dataTable.getColumnName(axis[X_AXIS]), values));
        } else if (dataTable.isDate(axis[X_AXIS]) || dataTable.isDateTime(axis[X_AXIS])) {
            DateAxis domainAxis = new DateAxis(dataTable.getColumnName(axis[X_AXIS]));
            domainAxis.setTimeZone(Tools.getPreferredTimeZone());
            plot.setDomainAxis(domainAxis);
        } else {
            if (logScales[X_AXIS]) {
                LogAxis domainAxis = new LogAxis(dataTable.getColumnName(axis[X_AXIS]));
                domainAxis.setStandardTickUnits(NumberAxis.createStandardTickUnits(Locale.US));
                plot.setDomainAxis(domainAxis);
            } else {
                NumberAxis domainAxis = new NumberAxis(dataTable.getColumnName(axis[X_AXIS]));
                domainAxis.setAutoRangeStickyZero(false);
                domainAxis.setAutoRangeIncludesZero(false);
                plot.setDomainAxis(domainAxis);
            }
        }
    }

    if (axis[X_AXIS] >= 0) {
        Range range = getRangeForDimension(axis[X_AXIS]);
        if (range != null) {
            plot.getDomainAxis().setRange(range, true, false);
        } else {
            plot.getDomainAxis().setAutoRange(true);
        }
    }

    plot.getDomainAxis().setLabelFont(LABEL_FONT_BOLD);
    plot.getDomainAxis().setTickLabelFont(LABEL_FONT);

    // rotate labels
    if (isLabelRotating()) {
        plot.getDomainAxis().setTickLabelsVisible(true);
        plot.getDomainAxis().setVerticalTickLabels(true);
    }

    // range axis
    if (axis[Y_AXIS] >= 0) {
        if (dataTable.isNominal(axis[Y_AXIS])) {
            String[] values = new String[dataTable.getNumberOfValues(axis[Y_AXIS])];
            for (int i = 0; i < values.length; i++) {
                values[i] = dataTable.mapIndex(axis[Y_AXIS], i);
            }
            plot.setRangeAxis(new SymbolAxis(dataTable.getColumnName(axis[Y_AXIS]), values));
        } else if (dataTable.isDate(axis[Y_AXIS]) || dataTable.isDateTime(axis[Y_AXIS])) {
            DateAxis rangeAxis = new DateAxis(dataTable.getColumnName(axis[Y_AXIS]));
            rangeAxis.setTimeZone(Tools.getPreferredTimeZone());
            plot.setRangeAxis(rangeAxis);
        } else {
            if (logScales[Y_AXIS]) {
                LogAxis rangeAxis = new LogAxis(dataTable.getColumnName(axis[Y_AXIS]));
                rangeAxis.setStandardTickUnits(NumberAxis.createStandardTickUnits(Locale.US));
                plot.setRangeAxis(rangeAxis);
            } else {
                NumberAxis rangeAxis = new NumberAxis(dataTable.getColumnName(axis[Y_AXIS]));
                rangeAxis.setAutoRangeStickyZero(false);
                rangeAxis.setAutoRangeIncludesZero(false);
                plot.setRangeAxis(rangeAxis);
            }
        }
    }
    plot.getRangeAxis().setLabelFont(LABEL_FONT_BOLD);
    plot.getRangeAxis().setTickLabelFont(LABEL_FONT);

    if (axis[Y_AXIS] >= 0) {
        Range range = getRangeForDimension(axis[Y_AXIS]);
        if (range != null) {
            plot.getRangeAxis().setRange(range, true, false);
        } else {
            plot.getRangeAxis().setAutoRange(true);
        }
    }

    // Chart Panel Settings
    AbstractChartPanel panel = getPlotterPanel();
    if (panel == null) {
        panel = createPanel(chart);

        // react to mouse clicks
        panel.addChartMouseListener(new ChartMouseListener() {

            @Override
            public void chartMouseClicked(ChartMouseEvent e) {
                if (e.getTrigger().getClickCount() > 1) {
                    if (e.getEntity() instanceof XYItemEntity) {
                        XYItemEntity entity = (XYItemEntity) e.getEntity();
                        if (entity != null) {
                            String id = idMap.get(new SeriesAndItem(entity.getSeriesIndex(), entity.getItem()));
                            if (id != null) {
                                ObjectVisualizer visualizer = ObjectVisualizerService
                                        .getVisualizerForObject(dataTable);
                                visualizer.startVisualization(id);
                            }
                        }
                    }
                }
            }

            @Override
            public void chartMouseMoved(ChartMouseEvent e) {
            }
        });

    } else {
        panel.setChart(chart);
    }

    // tooltips
    class CustomXYToolTipGenerator implements XYToolTipGenerator {

        public CustomXYToolTipGenerator() {
        }

        private String formatValue(int axis, double value) {
            if (dataTable.isNominal(axis)) {
                // TODO add mapping of value to nominal value
                return Tools.formatIntegerIfPossible(value);
            } else if (dataTable.isNumerical(axis)) {
                return Tools.formatIntegerIfPossible(value);
            } else if (dataTable.isDate(axis)) {
                return Tools.createDateAndFormat(value);
            } else if (dataTable.isTime(axis)) {
                return Tools.createTimeAndFormat(value);
            } else if (dataTable.isDateTime(axis)) {
                return Tools.createDateTimeAndFormat(value);
            }
            return "?";
        }

        @Override
        public String generateToolTip(XYDataset dataset, int row, int column) {
            String id = idMap.get(new SeriesAndItem(row, column));
            if (id != null) {
                return "<html><b>Id: " + id + "</b> (" + dataset.getSeriesKey(row) + ", "
                        + formatValue(axis[X_AXIS], dataset.getXValue(row, column)) + ", "
                        + formatValue(axis[Y_AXIS], dataset.getYValue(row, column)) + ")</html>";

            } else {
                return "<html>(" + dataset.getSeriesKey(row) + ", "
                        + formatValue(axis[X_AXIS], dataset.getXValue(row, column)) + ", "
                        + formatValue(axis[Y_AXIS], dataset.getYValue(row, column)) + ")</html>";
            }
        }
    }

    for (int i = 0; i < dataSet.getSeriesCount(); i++) {
        plot.getRenderer().setSeriesToolTipGenerator(i, new CustomXYToolTipGenerator());
    }
}

From source file:diet.gridr.g5k.gui.GanttChart.java

/**
 * Method creating the chart/*w  w w.  j  a v  a2 s.  co  m*/
 *
 * @param dataset dataset containing the data for the chart
 * @return a chart
 */
private JFreeChart createChart(XYZDataset dataset) {
    DateAxis xAxis = new DateAxis("Date");
    xAxis.setLowerMargin(0.0);
    xAxis.setUpperMargin(0.0);
    xAxis.setDateFormatOverride(new SimpleDateFormat(durationsFormatterArray[this.visualizationDuration]));
    xAxis.setRange(Calendar.getInstance().getTime(),
            new Date(System.currentTimeMillis() + HistoryUtil.durationsTimesArray[visualizationDuration]
                    - HistoryUtil.blockWidthsArray[visualizationDuration]));
    NumberAxis yAxis = new NumberAxis("Nodes");
    yAxis.setAutoRangeIncludesZero(false);
    yAxis.setInverted(true);
    yAxis.setLowerMargin(0.0);
    yAxis.setUpperMargin(0.0);
    yAxis.setRange(1, numberOfNodes);
    yAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    XYBlockRenderer renderer = new XYBlockRenderer();
    LookupPaintScale paintScale = new LookupPaintScale();
    for (int i = 0; i < jobsList.get(visualizationDuration).size(); i++) {
        // String jobId = jobsList.get(visualizationDuration).get(i).getId().substring(0,jobsList.get(visualizationDuration).get(i).getId().indexOf("."));
        String jobId = jobsList.get(visualizationDuration).get(i).getParameterValue(GridJob.KEY_GRID_JOB_ID);
        int seed = Integer.parseInt(jobId);
        Random rng = new Random(seed);
        Color tempColor = Color.red;
        int red = tempColor.getRed();
        int green = tempColor.getGreen();
        int blue = tempColor.getBlue();
        int redRNG = rng.nextInt(255);
        int greenRNG = rng.nextInt(255);
        int blueRNG = rng.nextInt(255);
        if (red == redRNG && green == greenRNG && blue == blueRNG) {
            tempColor = new Color(rng.nextInt(255), rng.nextInt(255), rng.nextInt(255));
        } else {
            tempColor = new Color(redRNG, greenRNG, blueRNG);
        }
        if (seed == 0)
            tempColor = Color.red;
        paintScale.add(new Double(i), tempColor);
    }
    renderer.setBlockWidth(HistoryUtil.blockWidthsArray[visualizationDuration]);
    renderer.setBlockAnchor(RectangleAnchor.TOP_LEFT);
    renderer.setPaintScale(paintScale);
    XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
    plot.setOrientation(PlotOrientation.VERTICAL);
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.black);
    plot.setRangeGridlinePaint(Color.black);
    JFreeChart chart = new JFreeChart("Gantt Chart activity for cluster " + siteName, plot);
    chart.removeLegend();
    chart.setBackgroundPaint(Color.white);
    LoggingManager.log(Level.CONFIG, LoggingManager.RESOURCESTOOL, this.getClass().getName(), "createChart",
            "Chart created");
    return chart;
}

From source file:org.owasp.webscarab.plugin.sessionid.swing.SessionIDPanel.java

private JFreeChart createChart(XYDataset data) {
    ValueAxis timeAxis = new DateAxis("Date/Time");
    timeAxis.setLowerMargin(0.02); // reduce the default margins on the time axis
    timeAxis.setUpperMargin(0.02);//from w ww.j a v a  2 s  .  co  m
    NumberAxis valueAxis = new NumberAxis("Value");
    valueAxis.setAutoRangeIncludesZero(false); // override default
    XYPlot plot = new XYPlot(data, timeAxis, valueAxis, null);
    plot.setRenderer(new StandardXYItemRenderer(StandardXYItemRenderer.SHAPES, null, null));
    JFreeChart chart = new JFreeChart("Cookie values over time", JFreeChart.DEFAULT_TITLE_FONT, plot, false);
    return chart;
}

From source file:de.xirp.chart.ChartManager.java

/**
 * Sets some values on the given/*  ww w .  java 2  s .c o m*/
 * {@link org.jfree.chart.plot.XYPlot} corresponding to some
 * options of the {@link de.xirp.chart.ChartOptions}
 * field. <br>
 * <br>
 * If <code>options.is(OptionName.SHOW_THRESHOLD)</code> is
 * <code>true</code> a threshold line is painted to the chart
 * using the <code>threshold</code> field. <br>
 * <br>
 * If <code>options.is(OptionName.USE_RELATIVE)</code> is
 * <code>true</code> the date axis of the plot gets a title
 * indicating that relative values are used. If the flag is
 * <code>false</code> the plot gets a title indicating that
 * absolute values are used.
 * 
 * @param plot
 *            The plot to alter.
 * @param start
 *            The start time.
 * @see de.xirp.chart.ChartOptions
 * @see org.jfree.chart.plot.XYPlot
 */
private static void setXYPlot(XYPlot plot, Date start) {
    plot.setNoDataMessage(NO_DATA_AVAILABLE);

    if (options.is(OptionName.SHOW_THRESHOLD)) {
        Marker marker = new ValueMarker(threshold);
        marker.setPaint(Color.orange);
        marker.setAlpha(0.8f);
        plot.addRangeMarker(marker);
    }

    if (options.is(OptionName.USE_RELATIVE)) {
        DateAxis axis = new DateAxis(I18n.getString("ChartManager.text.relativeTime")); //$NON-NLS-1$
        RelativeDateFormat rdf = new RelativeDateFormat(start);
        axis.setDateFormatOverride(rdf);
        plot.setDomainAxis(axis);
    } else {
        plot.setDomainAxis(new DateAxis(I18n.getString("ChartManager.text.absoluteTime"))); //$NON-NLS-1$
    }
}