List of usage examples for org.jfree.chart.renderer.xy XYErrorRenderer XYErrorRenderer
public XYErrorRenderer()
XYErrorRenderer
instance. From source file:org.esa.beam.visat.toolviews.stat.ProfilePlotPanel.java
@Override protected void initComponents() { getAlternativeView().initComponents(); dataset = new XYIntervalSeriesCollection(); this.chart = ChartFactory.createXYLineChart(CHART_TITLE, "Path in pixels", DEFAULT_SAMPLE_DATASET_NAME, dataset, PlotOrientation.VERTICAL, true, true, false); final XYPlot plot = chart.getXYPlot(); deviationRenderer = new DeviationRenderer(); deviationRenderer.setUseFillPaint(true); deviationRenderer.setBaseToolTipGenerator(new XYPlotToolTipGenerator()); deviationRenderer.setSeriesLinesVisible(0, true); deviationRenderer.setSeriesShapesVisible(0, false); deviationRenderer.setSeriesStroke(0, new BasicStroke(1.0f)); deviationRenderer.setSeriesPaint(0, StatisticChartStyling.SAMPLE_DATA_PAINT); deviationRenderer.setSeriesFillPaint(0, StatisticChartStyling.SAMPLE_DATA_FILL_PAINT); pointRenderer = new XYErrorRenderer(); pointRenderer.setUseFillPaint(true); pointRenderer.setBaseToolTipGenerator(new XYPlotToolTipGenerator()); pointRenderer.setSeriesLinesVisible(0, false); pointRenderer.setSeriesShapesVisible(0, true); pointRenderer.setSeriesStroke(0, new BasicStroke(1.0f)); pointRenderer.setSeriesPaint(0, StatisticChartStyling.SAMPLE_DATA_PAINT); pointRenderer.setSeriesFillPaint(0, StatisticChartStyling.SAMPLE_DATA_FILL_PAINT); pointRenderer.setSeriesShape(0, StatisticChartStyling.SAMPLE_DATA_POINT_SHAPE); configureRendererForCorrelativeData(deviationRenderer); configureRendererForCorrelativeData(pointRenderer); plot.setNoDataMessage(NO_DATA_MESSAGE); plot.setAxisOffset(new RectangleInsets(5, 5, 5, 5)); plot.setRenderer(deviationRenderer); final AxisChangeListener axisListener = new AxisChangeListener() { @Override//ww w . ja v a 2 s.c om public void axisChanged(AxisChangeEvent event) { adjustAxisControlComponents(); } }; final ValueAxis domainAxis = plot.getDomainAxis(); final ValueAxis rangeAxis = plot.getRangeAxis(); // allow transfer from bounds into min/max fields, if auto min/maxis enabled domainAxis.setAutoRange(true); rangeAxis.setAutoRange(true); domainAxis.addChangeListener(axisListener); rangeAxis.addChangeListener(axisListener); intervalMarkers = new HashSet<>(); xAxisRangeControl = new AxisRangeControl("X-Axis"); yAxisRangeControl = new AxisRangeControl("Y-Axis"); final PropertyChangeListener changeListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals(PROPERTY_NAME_MARK_SEGMENTS)) { updateDataSet(); } if (evt.getPropertyName().equals(PROPERTY_NAME_LOG_SCALED)) { updateScalingOfYAxis(); } updateUIState(); } }; xAxisRangeControl.getBindingContext().addPropertyChangeListener(changeListener); xAxisRangeControl.getBindingContext().getPropertySet() .addProperty(Property.create(PROPERTY_NAME_MARK_SEGMENTS, false)); xAxisRangeControl.getBindingContext().getPropertySet().getDescriptor(PROPERTY_NAME_MARK_SEGMENTS) .setDescription("Toggle whether to mark segments"); yAxisRangeControl.getBindingContext().addPropertyChangeListener(changeListener); yAxisRangeControl.getBindingContext().getPropertySet() .addProperty(Property.create(PROPERTY_NAME_LOG_SCALED, false)); yAxisRangeControl.getBindingContext().getPropertySet().getDescriptor(PROPERTY_NAME_LOG_SCALED) .setDescription("Toggle whether to use a logarithmic axis"); dataSourceConfig = new DataSourceConfig(); final BindingContext bindingContext = new BindingContext( PropertyContainer.createObjectBacked(dataSourceConfig)); JPanel middlePanel = createMiddlePanel(bindingContext); createUI(createChartPanel(chart), middlePanel, bindingContext); isInitialized = true; updateComponents(); }
From source file:org.gumtree.vis.awt.PlotFactory.java
/** * Creates a line chart (based on an {@link XYDataset}) with default * settings.// w w w . j a v a2 s . com * * @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 The chart. */ protected static JFreeChart createXYLineChart(String title, String xAxisLabel, String yAxisLabel, XYDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls) { if (orientation == null) { throw new IllegalArgumentException("Null 'orientation' argument."); } // NumberAxis xAxis = new NumberAxis(xAxisLabel); LogarithmizableAxis xAxis = new LogarithmizableAxis(xAxisLabel); boolean isLogX = false; try { isLogX = Boolean.valueOf(System.getProperty(LOGX_PROPERTY)); } catch (Exception e) { } xAxis.setLogarithmic(isLogX); // xAxis.setAutoRangeIncludesZero(false); xAxis.setAllowNegativesFlag(true); xAxis.setLowerMargin(0.02); xAxis.setUpperMargin(0.02); // NumberAxis yAxis = new NumberAxis(yAxisLabel); LogarithmizableAxis yAxis = new LogarithmizableAxis(yAxisLabel); boolean isLogY = false; try { isLogY = Boolean.valueOf(System.getProperty(LOGY_PROPERTY)); } catch (Exception e) { } yAxis.setLogarithmic(isLogY); yAxis.setAllowNegativesFlag(true); yAxis.setAutoRangeNextLogFlag(false); yAxis.setLowerMargin(0.02); yAxis.setUpperMargin(0.02); XYErrorRenderer renderer = new XYErrorRenderer(); renderer.setBaseLinesVisible(true); renderer.setBaseShapesVisible(false); renderer.setDrawYError(true); // XYItemRenderer renderer = new XYLineAndShapeRenderer(true, false); XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer); plot.setOrientation(orientation); if (tooltips) { renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator()); } if (urls) { renderer.setURLGenerator(new StandardXYURLGenerator()); } JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend); chartTheme.apply(chart); return chart; }
From source file:SciTK.PlotXYError.java
/** More (common) initialization routines */ private void init(String x_label, String y_label, String window_title) { chart = ChartFactory.createScatterPlot("", x_label, y_label, data, PlotOrientation.VERTICAL, false, true, false);/*from w ww .j a v a 2 s . c om*/ XYErrorRenderer renderer = new XYErrorRenderer(); XYPlot plot = chart.getXYPlot(); // the plot itself plot.setRenderer(renderer); // for some reason default is white, change it to black: setGridlineColor(Color.BLACK); super.window_title = window_title; super.initUI(); }
From source file:org.gumtree.vis.plot1d.Plot1D.java
/** * Creates a line chart (based on an {@link XYDataset}) with default * settings.//from w ww. j a va 2s. co m * * @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 The chart. */ public static JFreeChart createXYLineChart(String title, String xAxisLabel, String yAxisLabel, XYDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls) { if (orientation == null) { throw new IllegalArgumentException("Null 'orientation' argument."); } // NumberAxis xAxis = new NumberAxis(xAxisLabel); LogarithmizableAxis xAxis = new LogarithmizableAxis(xAxisLabel); xAxis.setLogarithmic(false); xAxis.setAutoRangeIncludesZero(false); xAxis.setAllowNegativesFlag(true); xAxis.setLowerMargin(0.02); xAxis.setUpperMargin(0.02); // NumberAxis yAxis = new NumberAxis(yAxisLabel); LogarithmizableAxis yAxis = new LogarithmizableAxis(yAxisLabel); yAxis.setAllowNegativesFlag(true); yAxis.setAutoRangeNextLogFlag(false); yAxis.setLowerMargin(0.02); yAxis.setUpperMargin(0.02); yAxis.setLogarithmic(false); XYErrorRenderer renderer = new XYErrorRenderer(); renderer.setBaseLinesVisible(true); renderer.setBaseShapesVisible(false); renderer.setDrawYError(true); // XYItemRenderer renderer = new XYLineAndShapeRenderer(true, false); XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer); plot.setOrientation(orientation); if (tooltips) { renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator()); } if (urls) { renderer.setURLGenerator(new StandardXYURLGenerator()); } JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend); chartTheme.apply(chart); return chart; }
From source file:weka.classifiers.timeseries.eval.graph.JFreeChartDriver.java
protected JFreeChart getPredictedStepsChart(TSForecaster forecaster, List<ErrorModule> preds, String targetName, List<Integer> stepsToPlot, int instanceNumOffset, Instances data) { if (forecaster instanceof TSLagUser && data != null) { TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker(); if (lagMaker.getAdjustForTrends() && !lagMaker.isUsingAnArtificialTimeIndex()) { // fill in any missing time stamps only data = new Instances(data); data = weka.classifiers.timeseries.core.Utils.replaceMissing(data, null, lagMaker.getTimeStampField(), true, lagMaker.getPeriodicity(), lagMaker.getSkipEntries()); }// w w w . java 2s . c o m } // set up a collection of predicted series XYIntervalSeriesCollection xyDataset = new XYIntervalSeriesCollection(); XYIntervalSeries targetSeries = new XYIntervalSeries(targetName, false, false); xyDataset.addSeries(targetSeries); // for (int i = 0; i < preds.size(); i++) { for (int z = 0; z < stepsToPlot.size(); z++) { int i = stepsToPlot.get(z); i--; // ignore out of range steps if (i < 0 || i >= preds.size()) { continue; } String step = "-steps"; if (i == 0) { step = "-step"; } targetSeries = new XYIntervalSeries(targetName + "_" + (i + 1) + step + "-ahead", false, false); xyDataset.addSeries(targetSeries); } ValueAxis timeAxis = null; NumberAxis valueAxis = new NumberAxis(""); valueAxis.setAutoRangeIncludesZero(false); int timeIndex = -1; boolean timeAxisIsDate = false; if (forecaster instanceof TSLagUser && data != null) { TSLagMaker lagMaker = ((TSLagUser) forecaster).getTSLagMaker(); if (!lagMaker.isUsingAnArtificialTimeIndex() && lagMaker.getAdjustForTrends()) { String timeName = lagMaker.getTimeStampField(); if (data.attribute(timeName).isDate()) { timeAxis = new DateAxis(""); timeAxisIsDate = true; timeIndex = data.attribute(timeName).index(); } } } if (timeAxis == null) { timeAxis = new NumberAxis(""); ((NumberAxis) timeAxis).setAutoRangeIncludesZero(false); } // now populate the series // for (int i = 0; i < preds.size(); i++) { boolean doneActual = false; boolean hasConfidenceIntervals = false; for (int z = 0; z < stepsToPlot.size(); z++) { int i = stepsToPlot.get(z); i--; // ignore out of range steps if (i < 0 || i >= preds.size()) { continue; } ErrorModule predsForStepI = preds.get(i); List<NumericPrediction> predsForTargetAtI = predsForStepI.getPredictionsForTarget(targetName); String step = "-steps"; if (i == 0) { step = "-step"; } int predIndex = xyDataset.indexOf(targetName + "_" + (i + 1) + step + "-ahead"); XYIntervalSeries predSeries = xyDataset.getSeries(predIndex); XYIntervalSeries actualSeries = null; if (!doneActual) { int actualIndex = xyDataset.indexOf(targetName); actualSeries = xyDataset.getSeries(actualIndex); } for (int j = 0; j < predsForTargetAtI.size(); j++) { double x = Utils.missingValue(); if (timeAxisIsDate) { if (instanceNumOffset + j + i < data.numInstances()) { x = data.instance(instanceNumOffset + j + i).value(timeIndex); } } else { x = instanceNumOffset + j + i; } double yPredicted = predsForTargetAtI.get(j).predicted(); double yHigh = yPredicted; double yLow = yPredicted; double[][] conf = predsForTargetAtI.get(j).predictionIntervals(); if (conf.length > 0) { yLow = conf[0][0]; yHigh = conf[0][1]; hasConfidenceIntervals = true; } if (!Utils.isMissingValue(x) && !Utils.isMissingValue(yPredicted)) { if (predSeries != null) { predSeries.add(x, x, x, yPredicted, yLow, yHigh); } // System.err.println("* " + yPredicted + " " + x); } if (!doneActual && actualSeries != null) { double yActual = predsForTargetAtI.get(j).actual(); if (!Utils.isMissingValue(x) && !Utils.isMissingValue(yActual)) { actualSeries.add(x, x, x, yActual, yActual, yActual); } } } if (actualSeries != null) { doneActual = true; } } // set up the chart String title = ""; for (int i : stepsToPlot) { title += i + ","; } title = title.substring(0, title.lastIndexOf(",")); title += " step-ahead predictions for " + targetName; /* * 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.setBaseLinesVisible(true); // renderer.setShapesFilled(true); XYPlot plot = new XYPlot(xyDataset, timeAxis, valueAxis, renderer); 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:org.esa.snap.rcp.statistics.ScatterPlotPanel.java
private void createUI() { final XYPlot plot = getPlot(); plot.setAxisOffset(new RectangleInsets(5, 5, 5, 5)); plot.setNoDataMessage(NO_DATA_MESSAGE); int confidenceDSIndex = 0; int regressionDSIndex = 1; int scatterpointsDSIndex = 2; plot.setDataset(confidenceDSIndex, acceptableDeviationDataset); plot.setDataset(regressionDSIndex, regressionDataset); plot.setDataset(scatterpointsDSIndex, scatterpointsDataset); plot.addAnnotation(r2Annotation); final DeviationRenderer identityRenderer = new DeviationRenderer(true, false); identityRenderer.setSeriesPaint(0, StatisticChartStyling.SAMPLE_DATA_PAINT); identityRenderer.setSeriesFillPaint(0, StatisticChartStyling.SAMPLE_DATA_FILL_PAINT); plot.setRenderer(confidenceDSIndex, identityRenderer); final DeviationRenderer regressionRenderer = new DeviationRenderer(true, false); regressionRenderer.setSeriesPaint(0, StatisticChartStyling.REGRESSION_DATA_PAINT); regressionRenderer.setSeriesFillPaint(0, StatisticChartStyling.REGRESSION_DATA_FILL_PAINT); plot.setRenderer(regressionDSIndex, regressionRenderer); final XYErrorRenderer scatterPointsRenderer = new XYErrorRenderer(); scatterPointsRenderer.setDrawXError(true); scatterPointsRenderer.setErrorStroke(new BasicStroke(1)); scatterPointsRenderer.setErrorPaint(StatisticChartStyling.CORRELATIVE_POINT_OUTLINE_PAINT); scatterPointsRenderer.setSeriesShape(0, StatisticChartStyling.CORRELATIVE_POINT_SHAPE); scatterPointsRenderer.setSeriesOutlinePaint(0, StatisticChartStyling.CORRELATIVE_POINT_OUTLINE_PAINT); scatterPointsRenderer.setSeriesFillPaint(0, StatisticChartStyling.CORRELATIVE_POINT_FILL_PAINT); scatterPointsRenderer.setSeriesLinesVisible(0, false); scatterPointsRenderer.setSeriesShapesVisible(0, true); scatterPointsRenderer.setSeriesOutlineStroke(0, new BasicStroke(1.0f)); scatterPointsRenderer.setSeriesToolTipGenerator(0, (dataset, series, item) -> { final XYIntervalSeriesCollection collection = (XYIntervalSeriesCollection) dataset; final Comparable key = collection.getSeriesKey(series); final double xValue = collection.getXValue(series, item); final double endYValue = collection.getEndYValue(series, item); final double yValue = collection.getYValue(series, item); return String.format("%s: mean = %6.2f, sigma = %6.2f | %s: value = %6.2f", getRasterName(), yValue, endYValue - yValue, key, xValue); });/*from ww w. ja v a2 s . co m*/ plot.setRenderer(scatterpointsDSIndex, scatterPointsRenderer); final boolean autoRangeIncludesZero = false; final boolean xLog = scatterPlotModel.xAxisLogScaled; final boolean yLog = scatterPlotModel.yAxisLogScaled; plot.setDomainAxis( StatisticChartStyling.updateScalingOfAxis(xLog, plot.getDomainAxis(), autoRangeIncludesZero)); plot.setRangeAxis( StatisticChartStyling.updateScalingOfAxis(yLog, plot.getRangeAxis(), autoRangeIncludesZero)); createUI(createChartPanel(chart), createInputParameterPanel(), bindingContext); plot.getDomainAxis().addChangeListener(domainAxisChangeListener); scatterPlotDisplay.setMouseWheelEnabled(true); scatterPlotDisplay.setMouseZoomable(true); }
From source file:org.esa.beam.timeseries.ui.graph.TimeSeriesGraphModel.java
private XYErrorRenderer createXYErrorRenderer() { final XYErrorRenderer renderer = new XYErrorRenderer(); renderer.setDrawXError(false);//from w w w .ja v a2 s.c o m renderer.setDrawYError(false); renderer.setBaseLinesVisible(true); renderer.setAutoPopulateSeriesStroke(false); renderer.setAutoPopulateSeriesPaint(false); renderer.setAutoPopulateSeriesFillPaint(false); renderer.setAutoPopulateSeriesOutlinePaint(false); renderer.setAutoPopulateSeriesOutlineStroke(false); renderer.setAutoPopulateSeriesShape(false); final StandardXYToolTipGenerator tipGenerator; tipGenerator = new StandardXYToolTipGenerator("Value: {2} Date: {1}", new SimpleDateFormat(), new DecimalFormat()); renderer.setBaseToolTipGenerator(tipGenerator); return renderer; }
From source file:org.esa.beam.visat.toolviews.stat.ScatterPlotPanel.java
private void createUI() { final XYPlot plot = getPlot(); plot.setAxisOffset(new RectangleInsets(5, 5, 5, 5)); plot.setNoDataMessage(NO_DATA_MESSAGE); plot.setDataset(CONFIDENCE_DSINDEX, acceptableDeviationDataset); plot.setDataset(REGRESSION_DSINDEX, regressionDataset); plot.setDataset(SCATTERPOINTS_DSINDEX, scatterpointsDataset); plot.addAnnotation(r2Annotation); final DeviationRenderer identityRenderer = new DeviationRenderer(true, false); identityRenderer.setSeriesPaint(0, StatisticChartStyling.SAMPLE_DATA_PAINT); identityRenderer.setSeriesFillPaint(0, StatisticChartStyling.SAMPLE_DATA_FILL_PAINT); plot.setRenderer(CONFIDENCE_DSINDEX, identityRenderer); final DeviationRenderer regressionRenderer = new DeviationRenderer(true, false); regressionRenderer.setSeriesPaint(0, StatisticChartStyling.REGRESSION_DATA_PAINT); regressionRenderer.setSeriesFillPaint(0, StatisticChartStyling.REGRESSION_DATA_FILL_PAINT); plot.setRenderer(REGRESSION_DSINDEX, regressionRenderer); final XYErrorRenderer scatterPointsRenderer = new XYErrorRenderer(); scatterPointsRenderer.setDrawXError(true); scatterPointsRenderer.setErrorStroke(new BasicStroke(1)); scatterPointsRenderer.setErrorPaint(StatisticChartStyling.CORRELATIVE_POINT_OUTLINE_PAINT); scatterPointsRenderer.setSeriesShape(0, StatisticChartStyling.CORRELATIVE_POINT_SHAPE); scatterPointsRenderer.setSeriesOutlinePaint(0, StatisticChartStyling.CORRELATIVE_POINT_OUTLINE_PAINT); scatterPointsRenderer.setSeriesFillPaint(0, StatisticChartStyling.CORRELATIVE_POINT_FILL_PAINT); scatterPointsRenderer.setSeriesLinesVisible(0, false); scatterPointsRenderer.setSeriesShapesVisible(0, true); scatterPointsRenderer.setSeriesOutlineStroke(0, new BasicStroke(1.0f)); scatterPointsRenderer.setSeriesToolTipGenerator(0, new XYToolTipGenerator() { @Override/*from www . j a v a 2s .co m*/ public String generateToolTip(XYDataset dataset, int series, int item) { final XYIntervalSeriesCollection collection = (XYIntervalSeriesCollection) dataset; final Comparable key = collection.getSeriesKey(series); final double xValue = collection.getXValue(series, item); final double endYValue = collection.getEndYValue(series, item); final double yValue = collection.getYValue(series, item); return String.format("%s: mean = %6.2f, sigma = %6.2f | %s: value = %6.2f", getRasterName(), yValue, endYValue - yValue, key, xValue); } }); plot.setRenderer(SCATTERPOINTS_DSINDEX, scatterPointsRenderer); final boolean autoRangeIncludesZero = false; final boolean xLog = scatterPlotModel.xAxisLogScaled; final boolean yLog = scatterPlotModel.yAxisLogScaled; plot.setDomainAxis( StatisticChartStyling.updateScalingOfAxis(xLog, plot.getDomainAxis(), autoRangeIncludesZero)); plot.setRangeAxis( StatisticChartStyling.updateScalingOfAxis(yLog, plot.getRangeAxis(), autoRangeIncludesZero)); createUI(createChartPanel(chart), createInputParameterPanel(), bindingContext); plot.getDomainAxis().addChangeListener(domainAxisChangeListener); scatterPlotDisplay.setMouseWheelEnabled(true); scatterPlotDisplay.setMouseZoomable(true); }
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 .j ava 2s .c om*/ } // 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:weka.gui.beans.JFreeChartOffscreenChartRenderer.java
/** * Render an XY scatter plot//from www. j a v a2 s . co m * * @param width the width of the resulting chart in pixels * @param height the height of the resulting chart in pixels * @param series a list of Instances - one for each series to be plotted * @param xAxis the name of the attribute for the x-axis (all series Instances * are expected to have an attribute of the same type with this name) * @param yAxis the name of the attribute for the y-axis (all series Instances * are expected to have an attribute of the same type with this name) * @param optionalArgs optional arguments to the renderer (may be null) * * @return a BufferedImage containing the chart * @throws Exception if there is a problem rendering the chart */ public BufferedImage renderXYScatterPlot(int width, int height, List<Instances> series, String xAxis, String yAxis, List<String> optionalArgs) throws Exception { String plotTitle = "Scatter Plot"; String userTitle = getOption(optionalArgs, "-title"); plotTitle = (userTitle != null) ? userTitle : plotTitle; String colorAtt = getOption(optionalArgs, "-color"); if (series.size() == 1 && colorAtt != null && colorAtt.length() > 0) { int colIndex = getIndexOfAttribute(series.get(0), colorAtt); if (colIndex >= 0 && series.get(0).attribute(colIndex).isNominal()) { // split single series out into multiple instances objects - one // per class series = splitToClasses(series.get(0), colIndex); for (Instances insts : series) { insts.setClassIndex(colIndex); } } } Instances masterInstances = series.get(0); int xAx = getIndexOfAttribute(masterInstances, xAxis); int yAx = getIndexOfAttribute(masterInstances, yAxis); if (xAx < 0) { xAx = 0; } if (yAx < 0) { yAx = 0; } // Set the axis names just in case we've been supplied with // /first, /last or /<num> xAxis = masterInstances.attribute(xAx).name(); yAxis = masterInstances.attribute(yAx).name(); // look for an additional attribute that stores the // shape sizes - could be either nominal or numeric errors. // We only use numeric error information String shapeSize = getOption(optionalArgs, "-shapeSize"); boolean nominalClass = (masterInstances.classIndex() >= 0 && masterInstances.classAttribute().isNominal()); int shapeSizeI = -1; if (shapeSize != null && shapeSize.length() > 0) { shapeSizeI = getIndexOfAttribute(masterInstances, shapeSize); } AbstractIntervalXYDataset xyDataset = null; if (shapeSizeI < 0 || nominalClass) { xyDataset = new XYSeriesCollection(); } else { xyDataset = new XYIntervalSeriesCollection(); } // add master series Series master = null; if (shapeSizeI < 0 || nominalClass) { master = new XYSeries(masterInstances.relationName()); } else { master = new XYIntervalSeries(masterInstances.relationName()); } AttributeStats xStats = masterInstances.attributeStats(xAx); AttributeStats yStats = masterInstances.attributeStats(yAx); double sizeRange = 0; double sizeMin = 0; if (shapeSizeI >= 0 && !nominalClass) { AttributeStats sStats = masterInstances.attributeStats(shapeSizeI); sizeRange = sStats.numericStats.max - sStats.numericStats.min; sizeMin = sStats.numericStats.min; } double xRange = 0; if (masterInstances.attribute(xAx).isNominal()) { xRange = masterInstances.attribute(xAx).numValues(); } else { xRange = xStats.numericStats.max - xStats.numericStats.min; } double yRange = 0; if (masterInstances.attribute(yAx).isNominal()) { xRange = masterInstances.attribute(yAx).numValues(); } else { yRange = yStats.numericStats.max - yStats.numericStats.min; } for (int i = 0; i < masterInstances.numInstances(); i++) { Instance inst = masterInstances.instance(i); if (!inst.isMissing(xAx) && !inst.isMissing(yAx)) { if (shapeSizeI < 0 || nominalClass) { ((XYSeries) master).add(inst.value(xAx), inst.value(yAx)); } else { double xBar = (inst.value(shapeSizeI) - sizeMin) / sizeRange; xBar *= (xRange / 5.0); // max of 1/5th the x range double yBar = (inst.value(shapeSizeI) - sizeMin) / sizeRange; yBar *= (yRange / 5.0); double x = inst.value(xAx); double y = inst.value(yAx); ((XYIntervalSeries) master).add(x, x - (xBar / 2.0), x + (xBar / 2.0), y, y - (yBar / 2.0), y + (yBar / 2.0)); } } } if (shapeSizeI < 0 || nominalClass) { ((XYSeriesCollection) xyDataset).addSeries((XYSeries) master); } else { ((XYIntervalSeriesCollection) xyDataset).addSeries((XYIntervalSeries) master); } // remaining series for (int i = 1; i < series.size(); i++) { Instances aSeriesI = series.get(i); Series aSeriesJ = null; if (shapeSizeI < 0 || nominalClass) { aSeriesJ = new XYSeries(aSeriesI.relationName()); } else { aSeriesJ = new XYIntervalSeries(aSeriesI.relationName()); } for (int j = 0; j < aSeriesI.numInstances(); j++) { Instance inst = aSeriesI.instance(j); if (!inst.isMissing(xAx) && !inst.isMissing(yAx)) { if (shapeSizeI < 0 || nominalClass) { ((XYSeries) aSeriesJ).add(inst.value(xAx), inst.value(yAx)); } else { double xBar = (inst.value(shapeSizeI) - sizeMin) / sizeRange; xBar *= (xRange / 5.0); // max of 1/10th the x range double yBar = (inst.value(shapeSizeI) - sizeMin) / sizeRange; yBar *= (yRange / 5.0); double x = inst.value(xAx); double y = inst.value(yAx); ((XYIntervalSeries) aSeriesJ).add(x, x - (xBar / 2.0), x + (xBar / 2.0), y, y - (yBar / 2.0), y + (yBar / 2.0)); } } } if (shapeSizeI < 0 || nominalClass) { ((XYSeriesCollection) xyDataset).addSeries((XYSeries) aSeriesJ); } else { ((XYIntervalSeriesCollection) xyDataset).addSeries((XYIntervalSeries) aSeriesJ); } } JFreeChart chart = ChartFactory.createXYLineChart(plotTitle, xAxis, yAxis, xyDataset, PlotOrientation.VERTICAL, true, false, false); chart.setBackgroundPaint(java.awt.Color.white); XYPlot plot = (XYPlot) chart.getPlot(); if (shapeSizeI < 0 || nominalClass) { XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(false, true); renderer.setBaseShapesFilled(false); plot.setRenderer(renderer); } else { XYErrorRenderer renderer = new XYErrorRenderer(); renderer.setDrawXError(true); renderer.setDrawYError(true); renderer.setBaseLinesVisible(false); plot.setRenderer(renderer); } BufferedImage image = chart.createBufferedImage(width, height); return image; }